This section describes how an array variable can be assigned with a list value. Array elements are referred by subscription notation as scalar expressions, like $identifier[i]. An unassigned array variable contains the (undef) value.
Array variables can be used in a Perl script under these rules:
An array variable should be assigned with a list value constructor using an assignment operation.
For example, @links = ("herongyang.com", "perl.org", "cpan.org").
Each element in an array variable can be referenced by a scalar expression with the index subscription notation,
$identifier[i]. The index i represents the ordered position of this element. The index value of the first element is 0.
For example, $links[0] is a scalar expression refers to the first element of the array variable @links.
Negative indexes can be used in the index subscription notation to refer array elements counted backward.
For example, $links[-1] is a scalar expression referring to the last element of the array variable @links.
The last index value of an array variable can be obtained by a special scalar value, $#identifier.
For example, $#links is a scalar value represents to the last index of the array variable @links.
One way to calculate the number of elements in an array is to use this last index notation, like $#links + 1.
If a new value is assigned to an element index value beyond the current last index,
the array will be extended to the new index value.
If you are trying to access an element with an index that has no value assigned, you will get the undef value.
For example, $links[$#links+1] is an undefined value, undef, because no value is assigned to an index beyond the current last index.
Here are some examples of array variable assignment operations with list value constructors:
Here is a Perl tutorial script on how to use array variables:
#- ArrayVariable.pl
#- Copyright (c) 1995 by Dr. Herong Yang, http://www.herongyang.com/
#
@links; # Undefined
print(@links, "\n");
@links = ("herongyang.com", "perl.org", "cpan.org");
print(@links, "\n"); # Defined now
$url = $links[0]; # Refers to the first element
print($url, "\n");
$links[2] = "google.com"; # Updates the 3rd element
print($links[2], "\n");
$links[9] = "yahoo.com"; # Extending the array size
print($links[9], "\n");
print($links[-10], "\n"); # Backward index
$size = $#links + 1; # last index value
print($size, "\n");
print ("undef", "\n") if ($links[100] == undef);
# Out of bound index