Perl arrays

Perl arrays

Introduction

Arrays are variables which contain lists of values. Each element in the list
is accessed, (or indexed), by a numeric subscript.

We can define an array in Perl as follows:

Or more compactly, we can use the qw operator to help us build a list of
quoted words. This frees us from having to bother with quoting each element or
separating them with commas:

Accessing an individual element of the array is easy, as this complete
example shows:

which outputs:

Note that we used the @ character (or sigil), to introduce the array as
a whole, (my @planets), and the $ character to access an element
within the array, ($planets[0]).

Iterating over an array

This code uses a for loop to iterate over each element in the @planets
array:

Which outputs:

Note that the foreach keyword is a synonym for for.

Adding to an array

We know that our array currently has five elements, the first element, (at
index 0), is mercury and the last, (at index 4), is jupiter.

We can assign a new value by simply creating a new index, as in:

But since our list of planets is still obviously incomplete, we can also
use the push function to push a list of values onto the end
of our array:

push() pushes the values of the list in its second argument onto
the end of the array supplied as its first argument.

Length of an array

You can determine the number of elements in an array using the scalar
function as follows:

Here is a complete example:

which outputs:

Alternatively, the $#array construction returns the subscript, or index,
of the last element of the array. Since Perl arrays start at element 0, this
number will
be one less than the length of the array. So the following code sample is
another way to display the length of the @planets array:

The $#array syntax can be used to create a numbered listing of our planets,
as in:

which outputs:

Removing the end of array

There is a certain amount of controversy in astronomical circles about
whether Pluto is really a planet, or just another Kuiper Belt object.

Let’s assume that a decision has been made to remove Pluto from the list
of planets. We can remove Pluto in our code as follows:

This produces the following output:

The pop function removes the last element from an array, (and returns it).

See also

Scroll to Top