3.1.15 shift and unshift

unshift takes two arguments: a list and a scalar (actually, it can take a list as the second argument) and inserts the second argument in the front of the list. Therefore, it is just like push except that push inserts element(s) at the end of the list whereas unshift inserts the new element(s) in the front. unshift returns the number of elements inserted.

shift is the counterpart of pop. shift moves the whole list to the left by one element, thus removing the first or the leftmost element. shift returns the element removed. The reduction of the list happens as a side effect.

Consider the following program that builds a list by unshifting elements onto it. These elements are put in the front of the array one by one by unshifting. If a list is unshifted, the elements of the second list are put in the front of the original list.

Program 3.13

#!/usr/bin/perl
use strict;
$" = "\n";
my (@friends, $friend);
my @friends99 = ('Michael Richter', 'Justin O\'Mallory', 'Rene Myers');
my @oldFriends = ('Brett Walters', 'Jeff Perich');

unshift @friends, "Hakan Kvarnstrom"; 
unshift @friends, @friends99;
unshift @friends, @oldFriends;
unshift @friends, "Matt Dawson";
while (@friends){
        $friend = shift (@friends);
        print "$friend\n";
}

The list @friends becomes empty at the end of the while loop. Before emptying, the list is printed in the following order.

Matt Dawson
Brett Walters
Jeff Perich
Michael Richter
Justin O'Malley
Rene Myers
Hakan Kvarnstrom

It must be pointed out that when the second argument to unshift is a list, the elements of this last are added to the front of the first argument list in the unreversed order.