AnyCompiler

Arrays

An array, sigil @, holds an ordered, growable list of scalars. push adds to the end, pop removes from the end, unshift adds to the front, shift removes from the front — the same four operations every array-backed list in any language supports, just named Perl's way.

use strict;
use warnings;

my @fruits = ("apple", "banana", "cherry");
push @fruits, "date";
print "After push: @fruits\n";

my $last = pop @fruits;
print "Popped: $last\n";

unshift @fruits, "apricot";
print "After unshift: @fruits\n";

my $first = shift @fruits;
print "Shifted: $first\n";
Output
After push: apple banana cherry date
Popped: date
After unshift: apricot apple banana cherry
Shifted: apricot

Individual elements are accessed with $array[index] — note the sigil switches to $ for a single element, since one element is a scalar, not a list. Negative indices count from the end. scalar(@array) forces scalar context (the same context lesson 10 covers in depth) and returns the element count. A range of elements is a slice, written @array[start..end] — note the sigil there is @, since a slice is itself a list.

use strict;
use warnings;

my @nums = (10, 20, 30, 40, 50);
print "Length: ", scalar(@nums), "\n";
print "First: $nums[0], Last: $nums[-1]\n";
print "Slice: @nums[1..3]\n";
Output
Length: 5
First: 10, Last: 50
Slice: 20 30 40

Next: control flow — if/elsif/else, unless, while, and until.

Practice exercise

Create my @nums = (1, 2, 3). Push 4 and 5 onto it, then print the array joined by commas using join(",", @nums).