You could add new items to the end of an array by simply storing them into elements with new, larger indices. But real Perl programmers don't use indices. 1 So in the next few sections, we'll present some ways to work with an array without using indices.
One common use of an array is as a stack of information, where new values are added to and removed from the right-hand side of the list. (This is the end with the "last" items in the array, the end with the highest index values.) These operations occur often enough to have their own special functions.
The pop operator takes the last element off of an array, and returns it:
@array = 5..9;
$fred = pop(@array); # $fred gets 9, @array now has (5, 6, 7, 8)
$barney = pop @array; # $barney gets 8, @array now has (5, 6, 7)
pop @array; # @array now has (5, 6). (The 7 is discarded.)
That last example uses pop "in a void context," which is merely a fancy way of saying the return value isn't going anywhere. There's nothing wrong with using pop in this way, if that's what you want.
If the array is empty, pop will leave it alone (since there is no element to remove), and it will return undef.
You may have noticed that pop may be used with or without parentheses. This is a general rule in Perl: as long as the meaning isn't changed by removing the parentheses, they're optional.
The converse operation is push, which adds an element (or a list of elements) to the
end of an array:
push(@array, 0); # @array now has (5, 6, 0)
push @array, 8; # @array now has (5, 6, 0, 8)
push @array, 1..10; # @array now has those ten new elements
@others = qw/ 9 0 2 1 0 /;
push @array, @others; # @array now has those five new elements (19 total)
Note that the first argument to push or the only argument for pop must be an array variable - pushing and popping would not make sense on a literal list.
Next: The shift and unshift Operators
[1]
Of course, we're joking. But there's a kernel of truth in this joke.
Indexing into arrays is not using Perl's strengths. If you use pop,
push, and similar operators that avoid using indexing, your code will
generally be faster than if you use many indices, as well as being more likely to
avoid "off-by-one" errors, often called "fencepost" errors. Occasionally, a
beginning Perl programmer (wanting to see how Perl's speed compares to Cs) will take,
say, a sorting algorithm optimized for C (with many array index operations), rewrite
it straightforward in Perl (again, with many index operations) and wonder why it's
so slow. The answer is that using a Stradivarius violin to pound nails should
not be considered a sound construction technique.
Return to the page from whence you came