Arrays and Lists
5.1 Creating and Accessing Arrays
use v5.36;
my @fruits = ('apple', 'banana', 'cherry');
my @numbers = (1..10);
my @words = qw(red green blue);
my @empty = ();
my @mixed = (1, 'two', 3.0, undef);
say $fruits[0]; # apple (an element is a scalar, so the sigil is $)
say $fruits[-1]; # cherry (negative index from the end)
say $#fruits; # 2 (last index)
say scalar @fruits; # 3 (count)
my $count = @fruits; # 3 (array in scalar context)
say "@fruits"; # "apple banana cherry" (interpolation joins with $")
my @slice = @fruits[0, 2]; # array slice: ('apple', 'cherry')
my ($first, @rest) = @fruits; # list assignment
@fruits[0, 1] = @fruits[1, 0]; # swap via slices
my %idx = %fruits[0, 1]; # key/value slice (5.20+): (0 => 'apple', 1 => 'banana')5.2 Modifying Arrays
push @fruits, 'date', 'elderberry'; # add to the end
my $last = pop @fruits; # remove from the end
unshift @fruits, 'apricot'; # add to the front
my $first = shift @fruits; # remove from the front
splice(@fruits, 1, 2); # remove 2 elements at index 1
splice(@fruits, 1, 0, 'kiwi', 'lime'); # insert at index 1
splice(@fruits, 1, 1, 'mango'); # replace one element
$#fruits = 1; # truncate to 2 elements
@fruits = (); # clear
delete $fruits[1]; # sets the element to undef (avoid; use splice)
exists $fruits[5]; # element exists?5.3 Iterating
for my $fruit (@fruits) { # foreach and for are synonyms
say $fruit;
}
for my $i (0 .. $#fruits) {
say "$i: $fruits[$i]";
}
while (my ($i, $v) = each @fruits) { # each on arrays (5.12+)
say "$i => $v";
}
for my ($i, $v) (builtin::indexed @fruits) { # multi-variable foreach (5.36+) + builtin::indexed (5.40 stable)
say "$i => $v";
}
say for @fruits; # statement modifier with the default variable $_
$_ *= 2 for @numbers; # the loop variable aliases elements (modifies the array!)5.4 Lists vs Arrays
A list is an ordered sequence of values (a temporary value). An array is a variable that holds a list.
Lists flatten: (1, (2, 3), @arr) becomes a single flat list. To nest data, use references (Module 12).
my ($a, $b, $c) = (1, 2); # $c is undef
($x, $y) = ($y, $x); # swap two existing variables
my $last = (10, 20, 30)[-1]; # list slice: 30
my ($n) = grep { $_ > 5 } @numbers; # first match via list assignment