3.1.4 The Index of the Last Element of an Array

The index of the last element of the array @friends can be obtained by writing $#friends. Therefore, if @friends has 20 elements in it, the value of $#friends is 19. So, one way to iterate over all elements of an array and perform an operation on each element is using a for loop and changing the loop index variable from an initial value of 0 and going up to the last index in steps of 1. In obtaining the index of the last element of an array, the $ prefix is used to indicate that number of elements is a scalar. All scalars in Perl have $ as the first character in their names. The following program takes an array and simply prints every element in it.

Program 3.1

#!/usr/bin/perl
use strict;
my (@friends, $i);
@friends = ('John Hart', 'Jeff Ellis', 'Brett Walters', 'Justin OMalley', 
    'Tom Toybee');
for ($i=0; $i <= $#friends; $i++){
    print (uc $friends[$i], "\n");
}

The program uppercases every element before printing it, one per line. uc is a function that takes one argument, and if the argument evaluates to a string, uppercases it.

Perl allows us to assign a value to the last index of an array. If @friends is an array and it has 5 elements, setting $#friends to a value less than 4, say 3, will cause Perl to discard the last element from the array. Assigning $#friends to a value more than 4, say 20, will cause Perl to allocate space for elements with index 5 through 20. The values of these elements will be undef to begin with. Perl expands or shrinks an array as elements are added or deleted. Hence, it is not necessary to assign a value to the last index in most situations.

If we want to make a list empty, we can assign the value of -1 to the corresponding $# variable. For example,

$#friends = -1;

is the same as

@friends = ();