Perl Arrays – a tutorial

Perl Arrays – a tutorial

Shlomi Fish

Introduction

(Editor’s note: Also see our arrays howto entry for a simple introduction to the topic)

Arrays are a sequence of variables, whose members can be retrieved and assigned to by using their indices. An index passed to an array may well be, and usually is, another variable.

To refer to the $i‘th element of the array @myarray, one uses the syntax $myarray[$i]. This element can be assigned to or its value can be retrieved, with the same notation.

Array indices are whole numbers and the first index is 0. As in the length of a string, the number of elements in an array is bounded only by the amount of available memory the computer has.

The following program prints the primes up to 200:

The notation scalar(@myarray) can be used to refer to the number of elements in an array. This number is equal to the maximal index which was assigned in the array plus one. You will also see the notation $#myarray which is equal to the maximal index itself.

Thus, for example, the above program could have been written as follows:

The ‘,’ operator

In Perl the comma (,) is an operator, which we often encounter in function
calls. The comma concatenates two arrays. We can use it to initialize an array in one call:

We can also use it to concatenate two existing arrays:

So why it is used in function calls? In Perl every function accepts an array of arguments and returns an array of return values. That’s why the comma is useful for calling functions which accept more than one argument.

Negative Indexes

The expression $myarray[-$n] is equivalent to
$myarray[scalar(@myarray)-$n. I.e: subscripts with negative indexes return
the $n‘th element from the end of the array. So to get the value of the last
element you can write $myarray[-1] and for the second last $myarray[-2],
etc.

Note that one should also make sure that array subscripts that are continuously
decremented will not underflow below 0, or else one will start getting the
elements from the end of the array.

The foreach loop

By using the foreach loop we can iterate over all the elements of an array, and perform the same set of operations on each one of them. Here’s an example:

The foreach loop in the example assigns each of the elements of the array which was passed to it to $i in turn, and executes the same set of commands for each value.

The for keyword and the .. operator

The for keyword in Perl means exactly the same as foreach and you can use either one arbitrarily.

In list context, the Perl range operator, .. returns a list containing
a sequence of consecutive integers. In the expression $a .. $b, for example,
the range operator returns the sequence of consecutive integers from $a
up to and including $b

Now one can fully understand the for $i (1 .. 10) construct that we used earlier.

Built-In Array Functions – push

The push function appends an element or an entire array to the end of an array variable. The syntax is push @array_to_append_to, @array_to_append or push @array, $elem1. For example, the primes program from earlier could be written as:

Notice that push is equivalent to typing @array = (@array, $extra_elem), but push is recommended because it is less error-prone and it executes faster.

Built-In Array Functions – pop

pop extracts the last element from an array and returns it. Here’s a short example to demonstrate it:

Built-In Array Functions – shift

shift extracts the first element of an array and returns it. The array will be changed to contain only the elements that were previously with the 1 to scalar(@array)-1 indexes.

Here’s the above example, while using shift instead of pop:

Built-In Array Functions – join

The syntax is join($separator, @array) and what it does is concatenate the elements of @array while putting $seperator in between. Here’s an example:

which outputs:

Built-In Array Functions – reverse

The reverse function returns the array which contains the elements of the array passed to it as argument in reverse. Here’s an example:

Note that by typing scalar(reverse($scalar)) you get the string that contains the characters of $scalar in reverse. scalar(reverse(@array)) concatenates the array into one string and then reverses its characters.

The x operator

The expression (@array) x $num_times returns an array that is composed of $num_times copies of @array one after the other. The expression $scalar x $num_times, on the other hand, returns a string containing $num_times copies of $scalar concatenated together string-wise.

Wrapping the left operand in parenthesis, (or not doing so), is therefore important. It is usually a good idea to assign the left part to a variable before using x so you’ll have the final expression ready.

Here’s an example to illustrate the use:

Can you guess what the output of this program will be?

Here’s a spoiler

See also

Scroll to Top