A slightly more interesting kind of variable is the array variable
which is a list of scalars (ie numbers and strings).
Array variables have the same format as scalar variables except that they
are prefixed by an @
symbol. The statement
@food = ("apples", "pears", "eels"); @music = ("whistle", "flute");assigns a three element list to the array variable @food and a two element list to the array variable @music.
The array is accessed by using indices starting from 0, and square brackets are used to specify the index. The expression
$food[2]returns eels. Notice that the @ has changed to a $ because eels is a scalar.
@moremusic = ("organ", @music, "harp"); @moremusic = ("organ", "whistle", "flute", "harp");This should suggest a way of adding elements to an array. A neater way of adding elements is to use the statement
push(@food, "eggs");which pushes eggs onto the end of the array @food. To push two or more items onto the array use one of the following forms:
push(@food, "eggs", "lard"); push(@food, ("eggs", "lard")); push(@food, @morefood);The push function returns the length of the new list.
To remove the last item from a list and return it use the pop function. From our original list the pop function returns eels and @food now has two elements:
$grub = pop(@food); # Now $grub = "eels"
It is also possible to assign an array to a scalar variable. As usual context is important. The line
$f = @food;assigns the length of @food, but
$f = "@food";turns the list into a string with a space between each element. This space can be replaced by any other string by changing the value of the special $" variable. This variable is just one of Perl's many special variables, most of which have odd names.
Arrays can also be used to make multiple assignments to scalar variables:
($a, $b) = ($c, $d); # Same as $a=$c; $b=$d; ($a, $b) = @food; # $a and $b are the first two # items of @food. ($a, @somefood) = @food; # $a is the first item of @food # @somefood is a list of the # others. (@somefood, $a) = @food; # @somefood is @food and # $a is undefined.The last assignment occurs because arrays are greedy, and @somefood will swallow up as much of @food as it can. Therefore that form is best avoided.
Finally, you may want to find the index of the last element of a list. To do this for the @food array use the expression
$#food
print @food; # By itself print "@food"; # Embedded in double quotes print @food.""; # In a scalar context