next up previous contents
Next: Using a List in Up: Arrays and Lists Previous: Arrays and Lists   Contents

The Basics

In perl notation, an array is a perl variable, whose name begins with an at-sign (@) and whose elements are accessed using numerical indices. A list is a parenthesized, comma-separated set of values, not necessarily assigned to a variable name. Perl treats such sets of values identically, whether they are stored as variables, or simply appear literally inside a program.

Perl arrays use zero-based indexing - the first element of the array has index 0, and, in general, the $n$th element has index $n - 1$. For each array you create, a special perl variable called $#arrayname is created, which contains the index of the last element in the array, that is one less than the number of elements actually contained in the array. If you need to change the size of an array, you can assign an appropriate value to this special variable. Thus, while the @nums array originally contains 5 elements, setting the variable $#nums to 3 truncates the array to a length of 4. (Don't forget the zero-based indexing!).

     @nums = (1,5,7,9,12);
     print "@nums";     # prints 1 5 7 9 12
     print $#nums;      # prints 4
     $#nums = 3;
     print "@nums";     # prints 1 5 7 9
You can use this technique to shorten an array in perl; alternatively the splice function (Section 4.4) can be used.

Note that the length function will not return the number of elements in an array; the length function returns the number of characters in scalar character data. See the following section for more information on how to determine the number of elements in an array.


next up previous contents
Next: Using a List in Up: Arrays and Lists Previous: Arrays and Lists   Contents
Phil Spector 2002-10-18