Perl shift Function



Perl shift function removes and returns the first element of an array, shortening the dimension of the array with 1.

This function is similar with pop function, which takes off the rightmost element of the array and opposite to unshift/push function that inserts a list at the beginning/end of the array.

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

In this short free tutorial I’ll show you how you can use Perl shift function inside your Perl script.

I’ll give you some code snippet examples to highlight some of the features of this function.


Click Below to See the Best

Perl How-to Snippet Collection

and Save Hours of Surfing on Internet!


To begin with, Perl shift function has two syntax forms:

shift(ARRAY)
shift()

The parenthesis can be omitted, but if you want your code more readable or avoid some precedence issues, you can use them. Anyway, I suggest you to use strict and warnings in your script, to avoid any possible typos or other issues. If the array used as argument is empty, this function will return the undef value.

The second form has no argument and in this case the Perl shift function will be applied on some special arrays:

  • @_ if you use it inside the lexical scope of a subroutine
  • @ARGV if you use it outside the body of a subroutine
Next, I’ll show you a simple example:

#!/usr/bin/perl

use strict;
use warnings;

# initialize an array
my @colors = qw(blue gray yellow white);
my $color = shift(@colors);
print "Removed: $color, Remained: @colors\n";
# it displays Removed: blue, Remained: gray yellow white

The first element of the array will be removed.



Using shift 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 remove the first element of the array, you guessed, we use the Perl shift function, and to add an element in front of the array we use the unshift 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
my @stack = qw(1 2 3 4 5 6 7);
# remove the first element
shift @stack;
print "@stack\n";
# stack is now (2 3 4 5 6 7) 
# insert an element in front of the stack
unshift(@stack, 1);
print "@stack\n";
# stack is now (1 2 3 4 5 6 7)

Another way of modeling an array as a stack is to use push & pop functions, instead of unshift & shift.

Using shift with a queue array


Using the Perl shift function you 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 the 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(one two three four);

# implement a forward queue array
push (@queue, "five");
shift @queue;
print "@queue\n";
# it displays: two three four five

Emulate a circular list with shift


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

#!/usr/bin/perl

use strict;
use warnings;

my @circularList = ('a'.. 'f');

push(@circularList, shift(@circularList));
print "\@circularList  = @circularList\n";
# it expects: @circularList  = b c d e f a

The shift function will return and take off the leftmost element of the circular list, i.e. 'a', and the push function will append this element at the end of the circular list. The elements of the circular list will move from right to left.

Using shift within a subroutine


Now I’ll show you an example about how you can use the Perl shift function within a subroutine. We want to define and use a subroutine that returns the sum of two numbers. Here is the snippet code:

#!/usr/bin/perl

use strict;
use warnings;

sub add {
   return (shift() + shift());
}

print "5 \+ 7 \= ", add(5, 7), "\n";
#it displays 5 + 7 = 12;

Perl has a specific way of handling subroutine arguments which are stored in the special @_ array. You can access the calling arguments either by accessing the @_ special array or accessing them one by one using $_[0], $_[1] and so on. In our example, we use Perl shift without parentheses that means we are using by default the @_ special array. The first shift will get and discard the first element of @_ and the second shift will get and discard the next element. The subroutine will return the sum of the two numbers.

It’s a common practice to get all the parameters passed into a subroutine with Perl shift function. We can assign these parameters to local variables, as follows:

#!/usr/bin/perl

use strict;
use warnings;

sub add {
   my $a = shift;
   my $b = shift;
   $a+$b;
}

print "5 \+ 7 \= ", add(5, 7), "\n";
#it displays 5 + 7 = 12;

Please note that our add subroutine looks like returning nothing, which is not entirely true. If we omit the return function at the end of a subroutine, Perl will return the last evaluated expression, in our case $a+$b.

We can rewrite the above subroutine for an indefinite number of arguments, as follows:

#!/usr/bin/perl

use strict;
use warnings;

sub add {
  my $sum = 0;
 
  while (@_) {
    $sum += shift;
  }
  return $sum;
}

print "Sum = ", add(5, 7, 9), "\n";
#it displays Sum = 21;

Please note the using of the while loop statement against the @_ special array and the addition assignment operator ("+=") here.

Please click here to download the Perl shift 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 shift 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. Given the following array of arrays:
my @AoA = ( 
  [ 'a1', 'b1', 1 ],
  [ 'a2', 'b2', 2 ],
  [ 'a3', 'b3', 3 ], 
);
use shift against each inner array of the @AoA array. Print the array after using shift, you must get the following output:
b1 1
b2 2
b3 3
2. Given the @AoA array from the previous exercise, use the shift function to remove the first element of the array (which is a reference to an inner array, in the same time remove the elements of the inner array too). Print the array after using shift:
a2 b2 2
a3 b3 3
3. Given the following array of hashes:
my @AoH = ( 
  { name => 'John', age => '21' },
  { name => 'Paul', age => '35' },
  { name => 'Mary', age => '50' }, 
);
remove the first element of this array and clear the hash referenced by this element. Next, print the array as:
Paul is 35 years old.
Mary is 50 years old.
4. Given the following hash of arrays:
my %HoA = (
      colors => ['blue', 'white', 'red', 'green', 'yellow'],
      shapes => ['square', 'triangle', 'circle', 'rectangle'],
          );
use shift against each inner array of the %HoA hash. Use push to save in a new array the removed elements. Print the hash as:
shapes => triangle circle rectangle
colors => white red green yellow
5. Initialize the @ARGV as follows:
@ARGV = ('red', 'white', 'green', 'blue');
a) print the first element of @ARGV
b) print all the elements of @ARGV
c) extract and remove the first argument
d) extract and remove the remaining arguments
6. Given the following array of arrays:
my @numbers = ([1, 2], [3, 4], [5, 6], [7]);
calculate the sum of all the numbers and next empty the inner arrays as well as the main array.
7. Write a subroutine where to find all the elements in a specific hash whose keys aren’t in a specific array. Use as array and hash the following:
my @array = (1, 2, 3, 4, 6, 7, 9, 12, 14);
my %hash = (1 => 'one', 4 => 'four', 
            8 => 'eight', 11 => 'eleven');
The subroutine must have two arguments: the first argument is a reference to the hash and the second argument is a reference to the array and must return a reference to a hash that contains the required elements. Next, print the created hash, you must have as output:
8 -> eight
11 -> eleven


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 (more)
        sort
        splice
        split
        sprintf
        substr
        tr
        uc
        ucfirst
        undef
        unpack
        unshift
        values

return from Perl shift Function to Perl Basics



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

Site Build It!