3.1.5 Accessing Elements Beyond the Last Element
Perl is very forgiving about many errors that other high level programming languages do not tolerate. When we use an array in Perl for the first time, we do not have to specify its maximum size. Even if we use
use strict;
strict vars;
or write use strict vars, we simply have to declare the name of the array and not its size. For example, the following is a declaration of an array using my.
my @friends;
In this declaration, there is no size specification.
In Perl, it is possible to access an element in an array beyond the last index. Thus, even if @friends has 5 elements, we can access its 56th element or 1010th element by writing $friends [55] or $friends [1009]. Perl will not complain because it does not perform array bounds checking. It will simply return undef as the value of any element beyond the last index. As a result of this lax attitude on the part of Perl, it may be sometimes difficult to debug programs that may misbehave due to array index crossing the array bound.
One can check if a certain element of an array has a defined value by using the defined function on an element with a specific index. Suppose we are working with an array @friends and it has 5 elements to begin with. We can assign a value to its 21st element, for instance. This causes the last index to increase to 20. Perl allocates space for all elements with index 5 through 20 although the elements with index 5 through 19 remain undefined. When Perl prints an undefined scalar, it prints nothing. The following program shows this. It is a modification of the previous program that now prints 6 values instead of 5.
Program 3.2
#!/usr/bin/perl
use strict;
my (@friends, $i);
@friends = ('John Hart', 'Jeff Ellis', 'Brett Walters', 'Blake Escort',
'Tom Toybee');
$friends [20] = 'Jeff Perich';
for ($i=0; $i <= $#friends; $i++){
if (defined $friends[$i]){
print "$i\t", (lc $friends[$i], "\n");
}
}
