Perl Arrays

Arrays @

Array constants are specified using parenthesis ( ) and the elements are separated with

commas. Perl arrays are like lists or collections in other languages since they can grow

and shrink, but in Perl they are just called “arrays”. Array variable names begin with the

at-sign (@). Unlike C, the assignment operator (=) works for arrays — an independent copy

of the array and its elements is made. Arrays may not contain other arrays as elements.

Perl has sort of a “1-deep” mentality. Actually, it’s possible to get around the 1-deep

constraint using “references”, but it’s no fun. Arrays work best if they just contain

scalars (strings and numbers). The elements in an array do not all need to be the same

type.

  @array = (1, 2, "hello");  ## a 3 element array 
@empty = (); ## the array with 0 elements
$x = 1; $y = 2; @nums = ($x + $y, $x - $y); ## @nums is now (3, -1)

Just as in C, square brackets [ ] are used to refer to elements, so $a[6] is the element

at index 6 in the array @a. As in C, array indexes start at 0. Notice that the syntax to

access an element begins with ‘$’ not ‘@’ — use ‘@’ only when referring to the whole

array (remember: all scalar expressions begin with $).

  @array = (1, 2, "hello", "there");   $array[0] = $array[0] + $array[1];## $array[0] is now 3   

Perl arrays are not bounds checked. If code attempts to read an element outside the array

size, undef is returned. If code writes outside the array size, the array grows

automatically to be big enough. Well written code probably should not rely on either of

those features.

  @array = (1, 2, "hello", "there");   $sum = $array[0] + $array[27];    ## $sum is now 1, since $array[27] returned undef   $array[99] = "the end";  ## array grows to be size 100   

When used in a scalar context, an array evaluates to its length. The “scalar” operator

will force the evaluation of something in a scalar context, so you can use scalar() to get

the length of an array. As an alternative to using scalar, the expression $#array is the

index of the last element of the array which is always one less than the length.

  @array = (1, 2, "hello", "there");   $len = @array;                  ## $len is now 4 (the length of @array)   $len = scalar(@array);  ## same as above, since $len represented a scalar   ## context anyway, but this is more explicit   
  @letters = ("a", "b", "c");   $i = $#letters;## $i is now 2   

That scalar(@array) is the way to refer to the length of an array is not a great moment in

the history of readable code. At least I haven’t showed you the even more vulgar forms

such as (0 + @a).

The sort operator (sort @a) returns a copy of the array sorted in ascending alphabetic

order. Note that sort does not change the original array. Here are some common ways to sort…

  (sort @array)  ## sort alphabetically, with uppercase first   (sort {$a  $b} @array)              ## sort numerically   (sort {$b cmp $a} @array)              ## sort reverse alphabetically   (sort {lc($a) cmp lc($b)} @array)      ## sort alphabetically, ignoring case (somewhat inefficient)   

The sort expression above pass a comparator function {…} to the sort operator, where the

special variables $a and $b are the two elements to compare — cmp is the built-in string

compare, and is the built-in numeric compare.

There’s a variant of array assignment that is used sometimes to assign several variables

at once. If an array on the left hand side of an assignment operation contains the names

of variables, the variables are assigned the corresponding values from the right hand

side.

($x, $y, $z) = (1, 2, “hello”, 4);

## assigns $x=1, $y=2, $z=”hello”, and the 4 is discarded

This type of assignment only works with scalars. If one of the values is an array, the

wrong thing happens (see “flattening” below).

Array Add/Remove/Splice Functions

These handy operators will add or remove an element from an array. These operators change

the array they operate on…

Operating at the “front” ($array[0]) end of the array…

shift(array)
returns the frontmost element and removes it from the array. Can be used

in a loop to gradually remove and examine all the elements in an array left to right. The

foreach operator, below, is another way to examine all the elements.

unshift(array, elem)
inserts an element at the front of the array. Opposite of shift.

Operating at the “back” ($array[$len-1]) end of the array…

pop(array)
returns the endmost element (right hand side) and removes it from the

array.

push(array, elem)
adds a single element to the end of the array. Opposite of pop.

splice(array, index, length, array2)
removes the section of the array defined by index

and length, and replaces that section with the elements from array2. If array2 is omitted,

splice()
simply deletes. For example, to delete the element at index $i from an array, use

splice(@array, $i, 1).

If you have found my website useful, please consider buying me a coffee below 😉