pop/push and shift/unshift

A Perl array is actually an implementation of the deque (double ended queue) concept. So Perl makes available to us two couples of functions (or operator - Perl looks a bit fuzzy on this distinction) on array: pop/push, to work on its tail; shift/unshift, for its head.

Let's create an array to do some testing:

my @array;
print "Empty array: @array\n";

I often find useful start doing a silly thing. For instance, what happens if I try to pop (that means: remove an item from the tail) an empty array?

my $item = pop @array;
print "Tried to pop but there was nothing in the array!\n" if(!defined $item);

We get no error, simply the result is set to undefined. Notice that I used the (funny) perl inverted syntax for "if", that is quite cool in a case like this.

Remember that for Perl the zero-lenght string, "", is considered equivalent to zero, that's why I had to check the result using the defined operator:

push @array, "";
$item = pop @array;
print "I've popped \"$item\" from the array\n" if(defined $item);

As a bonus, in the previous piece of code we have even seen how to use push to add an element at the end of an array. Actually, since that specific array was empty there was not much to see. Better if we push a couple of items, one after the other:

push @array, "one";
push @array, "two";
print "Array now is: @array\n";
$item = pop @array;
print "I've popped \"$item\" from the array\n";

The couple of functions shift/unshift work just the same, but at the beginning of the array:

unshift @array, "three";
print "Array now is: @array\n";
shift @array;
$item = shift @array;
print "I've shifted \"$item\" from the array\n";

Exactely as pop, also shift returns an undefined value when we try to act on an empty array:

$item = shift @array;
print "Tried to shift but there was no item in the array!\n" if(!defined $item);

Chapter 3 of Beginning Perl by Simon Cozens is about arrays and associative arrays (hashes).

No comments:

Post a Comment