3.3.2 Associated Scalars
Every time an array variable is declared, a special set of scalar
variables automatically springs into existence, and those scalars change
along with changes in the array with which they are associated.
First of all, for an array, @array
, of n elements. There
are scalar variables $array[0]
, $array[1]
, ...,
$array[n-1]
that contain first, second, third, ...,
nth elements in the array, respectively. The variables in this
format are full-fledged scalar variables. This means that anything you
can do with a scalar variable, you can do with these elements. This
provides a way to access array elements by subscript. In addition, it
provides a way to change, modify and update individual elements without
actually using the @array
variable.
Another scalar variable that is associated to any array variable,
@array
, is $#array
. This variable always contains the
subscript of the last element in the array. In other words,
$array[$#array]
is always the last element of the array. The
length of the array is always $#array + 1
. Again, you are
permitted to do anything with this variable that you can normally do
with any other scalar variable; however, you must always make sure to
leave the value as an integer greater than or equal to -1. In fact, if
you know an array is going to grow very large quickly, you probably want
to set this variable to a very high value. When you change the value of
$#array
, you not only resize the array for your use, you also
direct Perl to allocate a specific amount of space for @array
.
Here are a few examples that use the associated scalar variables for an
array:
use strict;
my @someStuff = qw/Hello and
welcome/; # @someStuff: an array of 3 elements
$#someStuff = 0; # @someStuff now is simply ("Hello")
$someStuff[1] = "Joe"; # Now @someStuff is ("Hello", "Joe")
$#someStuff = -1; # @someStuff is now empty
@someStuff = (); # does same thing as previous line