3.1.9 An Array in a Scalar Context
When an array is used in a scalar context, the number of elements in the array is returned by Perl, as the value of the array. For example, if we write
$friendCount = @friends;
the value of $friendCount is set to the number of elements in @friends. A scalar context is one in which a scalar value is required. Here, to the left of the assignment statement, we have a scalar $friendCount. This makes the context a scalar one. If @friends has 5 elements, $friendCount will have the value 5.
The fact that, in a scalar context, an array variable gives the number of elements (not the last index) in an array is quite frequently used in loops as a condition. This can be used in a situation in which, inside the loop, elements of the array are consumed one by one, and the iteration ends when all elements are consumed. We will see an example of such a loop when we discuss the push and pop functions later in this section.
Perl also has a built-in function called scalar that transforms a list into a scalar. That is, it returns the length of a list. Thus,
$friendCount = scalar(@friends);
gives the number of elements in an array. If there are undef elements in an array, they are counted as well. The following program illustrates this discussion.
#!/usr/bin/perl
#file array-scalar.pl
use strict;
my (@friends);
@friends = ('Matthew Gustafson', 'Brian Freeman', 'Justin OMalley');
print "I have ", scalar (@friends), " new friends\n";
print "Once again, I have ", $#friends + 1 , " new friends\n";
$friends [10] = 'Adam Lawler';
$friends [14] = "Nathan Ekenberg";
$friends [20] = "Luke Warner";
print "I have ", scalar (@friends), " new friends\n";
print "Once again, I have ", $#friends + 1 , " new friends\n";
The output of this program is given below.
I have 3 new friends Once again, I have 3 new friends I have 21 new friends Once again, I have 21 new friends
