Perl scripts can have arrays (or ``lists'') consisting of numeric values or strings. Entire array variables are prefixed with an ``at'' sign (@). It is also possible to assign to the array elements by name. Here are some examples of valid Perl array assignments:
@numbers = (3,1,4,1,5,9); @letters = ("this","is","a","test"); ($word,$another_word) = ("one","two");
Of course, Perl array elements can also be referenced by index. By default, Perl arrays start at 0. Perl array references look like this:
$blah[2] = 2.718281828; $message[12] = "core dumped\n";
Note that since an array element is a scalar, it is prefixed by a $.
The $# construct is used to find out the last valid index of an array rather than its size. The $[ variable indicates the base index of arrays in a Perl script. By default, this value is 0. Here is a code fragment which tells you the number of elements in an array:
# assume that @a is an array with a bunch of interesting elements $n = $#a - $[ + 1; print "array a has $n elements\n";
$[ can be reset to use a different base index for arrays. To have FORTRAN-style array indexing, set $[ to 1.
Arrays are expanded dynamically. You need only assign to new array elements as you need them. You can pre-allocate array memory by assigning to its $# value. For instance:
$#months = 11; # array @months has elements 0..11
Perl has operators and functions to do just about anything one would need to do to an array. There are facilities for pushing, popping, appending, slicing, and concatenating arrays.
Perl can only do one-dimensional arrays but there are ways to fake multi-dimensional arrays.