Arrays

  • A named list
  • Dynamically sized
  • 0-based index
  • Can push or pop an array (the end of the array is treated like the top of a stack)
  • Prefixed by @ to refer to the entire array or a slice of the array
  • Prefixed by $ to refer to an indexed element of the array
  • Prefixed by $# to refer to the index number of the last element (0-based)
  • When @array_name is used in a scalar context (where a number would usually be used), the resulting value is the number of elements in the array.
@arr       # array
@arr # array size (when used as a number)

$arr[n] # element [n]
$#arr   # element number (last element)
@arr            # the entire array
@arr[2] # a subarray consisting of the element at index [2]
@arr[0, 1, 3]  # a subarray consisting of the elements at indexes [0], [1], and [3]
$arr[3] # the element at index [3]

@arr + 0 # array length
scalar(@arr) # array length
my @arr = ('one', 'two');    # Named array (parentheses)
['one', 'two']; # Reference to an anonymous array (square brackets)
[@arr]; # Reference to an anonymous copy of the array (square brackets)

Functions

push
push(@array, LIST)
  • Adds a list to the end of the array
pop
pop(@array)
  • Removes and returns the last element of the array
shift
shift(@array)
  • Removes and returns the first element of the array
unshift
unshift(@array, LIST)
  • Adds a list to the front of the array
scalar
scalar(@array)
  • Returns the number of elements in the array

Examples

if (@arr1 == 5) {    # If there are exactly 5 elements in the array
statements;
}
my @arr = ("zero", "one", "two");
my @arr2 = @arr[0, 1]; # Slice: ("zero", "one")

my $arr_ref = ["zero", "one", "two"]; # Reference to an anonymous array (using square brackets instead of parentheses)

my ($a, $b, $c) = @arr;
my @arr = ();                  # Empty array

my $arr_ref = []; # Reference to an anonymous empty array (using square brackets instead of parentheses)
# Convert an array reference into a formatted string: (one, two, ...)
sub array_to_string {
my $arr_ref = shift;
return '(' . join(", ", @$arr_ref) . ')';
}

# Sample use
my @arr = ("one", "two", "three");
print array_to_string(\@arr); # Pass a reference to the array

print array_to_string( ["one", "two", "three"] ); # Pass a reference to an anonymous array (square brackets)
print array_to_string( [@arr] ); # Pass a reference to an anonymous copy of the array