More interesting kind of variables in perl is the array variable which are nothing but a
list of scalars entities (i'e numbers and strings). Array variables do have the same
format as that of a scalar variables except that they are prefixed by a symbol @.
A D V E R T I S E M E N T
Perl Array variables
The following statement assigns three elements list to the array variable "@fruit" and a two
element list to another array variable "@music".
The array element is accessed by using the indices starting from 0. Square brackets are
used to specify the index number of the element.
$fruit[2]
The Array Assignments
As in all of Perl, the same expression in a different context can produce a different
result. The first assignment which is given below explodes the @music variable so
that it is equivalent to the second assignment.
This should suggest a way for adding elements to an array. A cleaner way to add
elements is by using the following statement
push(@fruit, "eggs");
Here eggs is pushed into the end of the array @fruit. To push more than one item into
the array use one of the following method. The push function here returns the length of
the new list that is formed by adding more elements.
To remove the last item from the list and return it, we use the pop function.
From our original list the pop function returns eels
and @food now has two elements:
$grub = pop(@fruit); # Now $grub = "grape"
Here it is also possible to assign array to a scalar variable. As usual the context is
important. The following line assigns the length of @fruit,
$f = @fruit;
but the following statement turns the list into string with the space between each
element.This space can be replaced by any of the other string by changing the value of the
special variable "$". This variable is just one among Perl's many special variables,
most of them which have odd names.
$f = "@fruit";
We can make multiple assignments to scalar variables using arrays:
($x, $y) = ($z, $p); # Same as $x=$z; $y=$p;
($x, $y) = @fruit; # $x and $y are the first two
# items of @fruit.
($x, @somefood) = @fruit; # $y is the first item of @fruit
# @somefood is a list of the
# others.
(@somefood, $x) = @fruit; # @somefood is @fruit and
# $x is undefined.
The last assignment occurs because arrays seems to be greedy, and @somefood will take up as
much of @fruit as it can. Therefore this form is best avoided.
Finally, you may want to find out the index of the last element of list. To do this for the
@fruit array use the following expression
$#fruit;
How to Display arrays
As the context is important, it should not be too surprising that the following code
will produce a different result:
print @fruit; # By itself
print "@fruit"; # Embedded in double quotes
print @fruit.""; # In a scalar context