3.1.6 Elements Prior to Index 0
Perl allows a programmer to use negative integer indices to access elements of an array. The index -1 indexes the last element, -2 obtains the element before the last, etc. Thus, if n is the total number of elements in an array, the index -n gives the first element of the array. Negative indices can be used down to -n. Use of the index -(n+1) or smaller gives an error. In addition, setting the $# variable that gives the index of the last element of the array, to -1, empties the list. The following program illustrates the discussion in this paragraph very clearly.
#!/usr/bin/perl
#file arrayindex.pl
use strict;
my (@array);
@array = (1, 2, 3, 4, 5);
print "array = ", join (" ", @array), "\n";
#print the last element, the element before last, the element before that, etc.
print "\$array [-1] = ", $array [-1], "\n";
print "\$array [-2] = ", $array [-2], "\n";
print "\$array [-3] = ", $array [-3], "\n";
print "\$array [-4] = ", $array [-4], "\n";
print "\$array [-5] = ", $array [-5], "\n";
print "\$array [-6] = ", $array [-6], "\n";
#Changes the last element of an array
$array [-1] = 2;
print "array = ", join (" ", @array), "\n";
$array [-3] = 33;
$array [-4] = 44;
#The following if used is an error; it is commented here
#$array [-7] = 77;};
print "array = ", join (" ", @array), "\n";
#Empty an array
$#array = -1;
print "array = ", join (" ", @array), "\n";
The output of this program is given below. Please clearly understand the output to know how negative indices work.
array = 1 2 3 4 5 $array [-1] = 5 $array [-2] = 4 $array [-3] = 3 $array [-4] = 2 $array [-5] = 1 $array [-6] = array = 1 2 3 4 2 array = 1 44 33 4 2 array =
When nothing is printed, it means the value is undefined or does not exist.
