Array Variables
Beginning |
Previous |
Next
Creating Arrays
Arrays, also called lists, are created a variety of ways, some of
which are listed below:
@a = (4, 2, 6); # create them yourself
@b = ($f, 5.4); # use other variables to create them
# function that returns an array
@c = readdir (DIR, grep (/^\.\.?$/, @files));
@d = (); # create an empty array
Starting Index
An array index begin with zero (0), as in C, by default, but can be
changed by setting the special variable $[ (to be covered
later) to the starting index, eg, 1.
Accessing Individual Elements
An array starts with the "@" symbol, but to
reference an element, you use the "$" with an
array element "[n]", since that single value
itself is a scalar. If
@a = ('abc', 'def', 'ghi');
then the second element, a scalar, would be referenced, and printed, as:
print $a[1];
The Length of an Array
When you use an array in a scalar context, the value returned is the
length of the array, as in:
$length = @some_array;
There is a special way to specify the index of the
last element of any array, namely, $#ArrayName. This get created
automatically for you when the array comes into existance. You can
also set it manually. So to get the last element in the
array, you can say:
$last_element = $some_array[$#some_array];
Arrays are not fixed length but can grow and shrink as needed, for example:
@a = (0 .. 99); # automatically fill @a with consecutive
# integers from 0 to 99
@a = (@a, 10, 11, 12); # add more elements to the end
$b = shift (@a); # load first element into $b and shift every
# element by one
$#c = 10000; # preallocate @c w/ 10,000 elements (possible
# performace benefit)
Beginning |
Previous |
Next
Last Modified: $Date: 1997/05/02 07:17:33 $