[prev] [index] [next]

Arrays (Lists) (cont)

Arrays can be accessed element-at-a-time using the for loop:

@nums = (23, 95, 33, 42, 17, 87);
$sum = 0;
for ($i = 0; $i < @nums; $i++) {   # @nums gives length
    $sum += $nums[$i];
}
$sum = 0;
foreach $num (@nums) { sum += $num; }

push and pop act on the "right-hand" end of an array:

                   # Value of @a
@a = (1,3,5);      # (1,3,5)
push @a, 7;        # (1,3,5,7)
$x = pop @a;       # (1,3,5,7), $x == 7
$y = pop @a;       # (1,3,5), $y == 5