Perl unshift Function



The Perl unshift function inserts a list at the beginning of an array and returns the number of elements of the array after the insertion.

Practically, the whole list is prepended at the beginning of the array, so the prepended elements stay in the same order like in the original list.

If you want to reverse the order of elements in the list, you can use the reverse function.

The Perl unshift function is similar with push function, which appends the list at the end of the array and opposite to shift/pop function that takes off an element at the beginning/end of the array.

In connection with shift, pop and push, this function can be used to simulate queues and stacks in Perl.


Click Below to See the Best

Perl How-to Snippet Collection

and Save Hours of Surfing on Internet!


If you have any concerns about how long it takes to run repeatedly the Perl unshift function with a larger list, you must know that an array is allocated larger than needed so that there is enough room to grow in both directions, either you use unshift or push to add new elements. Thus in most cases, there is no need for Perl to reallocate the entire structure array and so decrease the efficiency. For a deep digging about this subject, I suggest you to follow this.



Now, the syntax form:

unshift (ARRAY, LIST)

The first argument of the Perl unshift function will tell you which array to operate on, and the second let you specify the elements to be added to the array. Like in the case of other built-in functions, the parentheses are optional.

The next short code snippet will show how you can use it:

#!/usr/bin/perl

use strict;
use warnings;

my @names = qw(John Peter Mary);
my $size = unshift @names, 'Alice', 'Tom';
# or my $size = unshift @names, ('Alice', 'Tom');
# or my $size = unshift (@names, 'Alice', 'Tom');

print "Size = $size, \@names = @names\n";
# displays Size = 5, @names = Alice Tom John Peter Mary 

The next two examples are about how you can model an array like a stack or a queue by using the unshift function.

Using unshift with a stack array


We can treat a stack as an unbounded array of things. We can simply treat an array like a stack, by adding or removing elements at the beginning of the array. In order to insert an element at the beginning of an array, you guessed, we use Perl unshift function, and to remove the first element of the array shift function. The shift & unshift functions treat the "left hand side" of the array as the top of the stack. Please take a look at the following example:

#!/usr/bin/perl

use strict;
use warnings;

# initialize an array with some operators
my @stack = qw(+ += - -= * *=);
# remove the first element
shift @stack;
print "@stack\n";
# stack is now (+= - -= * *=) 
# insert an element in front of the stack
unshift(@stack, '%');
print "@stack\n";
# stack is now (% += - -= * *=)  

Another way of modeling an array as a stack is to use push & pop functions, instead of unshift & shift. The push & pop functions treat the "right hand side" of the array as the top of the stack.

Using unshift with a queue array


Using the Perl unshift function we can very easily manipulate an array as a queue. So, you can use either push & shift to manipulate the array as a forward queue (push to enqueue onto the end of the array and shift to dequeue from the front of the array) or unshift & pop to manipulate the array as a backward queue (unshift to enqueue in front of he array and pop to dequeue onto the end of the array). See the following example:

#!/usr/bin/perl

use strict;
use warnings;

# initialize an array
my @queue = qw(two three four five);

# implement a backward queue array
unshift (@queue, "one");
pop @queue;
print "@queue\n";
# it displays one two three four

Emulate a circular list with unshift


You can very easily emulate a simple circular list using unshift and pop (or push and shift). Look at the following short code snippet:

#!/usr/bin/perl

use strict;
use warnings;

my @circularList = ('a'.. 'f');
unshift(@circularList, pop(@circularList));
print "\@circularList  = @circularList\n";
# it expects @circularList  = f a b c d e

The pop function will return and take off the rightmost element of the circular list, i.e. 'f', and the unshift function will insert this element at the front of the circular list. The elements of the circular list will move from left to right.

Please click here to download the Perl unshift script with all the above examples included.

Exercises


Through these exercises you have the opportunity to try yourself to write some script code where you can use the Perl unshift function. These exercises are completely covered in my Perl Functions for Real Arrays where I show you how to play with this important function in detail.

1. You have a matrix represented as an array of arrays (@AoA). Use the unshift function to insert a column (@column) at the beginning of this matrix. You can use these arrays:
my @AoA = (
            [12, 02, 34],
            [29, 22, 89],
            [11, 35, -5],
          );
my @column = (1, 2, 3);
Finally, print the @AoA array, the output is:
1 12 2 34
2 29 22 89
3 11 35 -5
2. You have a matrix represented as an array of arrays (@AoA). Use the unshift function to insert a row (@row) at the beginning of this matrix. You can use these arrays:
my @AoA = (
            [12, 02, 34],
            [29, 22, 89],
            [11, 35, -5],
          );
my @row = (1, 2, 3);
Finally, print the @AoA array, the output is:
1 2 3
12 2 34
29 22 89
11 35 -5
3. Insert a new element (name=''Mary, age='50') at the beginning of the following array of hashes (@AoH):
my @AoH = ( 
  { name => 'John', age => '21' },
  { name => 'Paul', age => '35' },  
);
After inserting, print the @AoH array as:
Mary is 50 years old.
John is 21 years old.
Paul is 35 years old.
4. Given the following hash of arrays (%HoA):
my %HoA = ( 
  a => [qw(abacus ant antique asset)],
  b => [qw(basket bed bird)],  
  c => [qw(car cinema)],
);
insert a list of elements ('ball', 'belly') in front of the inner array corresponding to the 'b' hash key. Print the hash of arrays as:
c => car cinema
a => abacus ant antique asset
b => ball belly basket bed bird


A-N-Y-O-N-E Can Learn and Master Perl!
And That Includes YOU!


Check these how-to tutorial eBooks (PDF format):


Table of Contents:

A Perl Script
Install Perl
Running Perl
Perl Data Types
Perl Variables
Perl Operators
Perl Lists
Perl Arrays
    Array Size
    Array Length
Perl Hashes
Perl Statements
    Perl if
    Perl unless
    Perl switch
    Perl while
    Perl do-while
    Perl until
    Perl do-until
    Perl for
    Perl foreach
Built-in Perl Functions
    Functions by Category
        String Functions
        Regular Expressions and Pattern Matching
        List Functions
        Array Functions
        Hash Functions
        Miscellaneous Functions
    Functions in alphabetical order
        chomp
        chop
        chr
        crypt
        defined
        delete
        each
        exists
        grep
        hex
        index
        join
        keys
        lc
        lcfirst
        length
        map
        oct
        ord
        pack
        pop
        push
        q
        qq
        qw
        reverse
        rindex
        scalar
        shift
        sort
        splice
        split
        sprintf
        substr
        tr
        uc
        ucfirst
        undef
        unpack
        unshift (more)
        values

return from Perl unshift Function to Perl Basics



Would you like to create your own website like this one?
Hit the Alarm Clock!

Site Build It!