Home
FREE Newsletter
Perl How To
Perl Books
Perl Basics
Perl Editors
Perl Modules
Perl Database
Net Programming
Sitemap
About Me
Contact Me
Blog
 

Perl shift Function



NEW!!!

Check my new resource:    Perl How To Tutorial eBooks



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 snippet code examples to highlight some of the features of this function.

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.


Check my new How To Tutorial eBooks (PDF format):

to see a lot of fully commented examples that help you use the Perl statements and the Perl buit-in functions in your scripts.



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 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.



Subscribe now to my FREE newsletter
(regarding tips and tricks to manipulate multidimensional
arrays and hashes in Perl)

and you'll receive a link to download for FREE my Perl chomp Function Tutorial eBook (a $7.50 value), it's a bonus for you and I hope you'll enjoy it. You can see its Table of Contents here (if you subscribe to my free newsletter, you don't have to pay for this eBook or use your paypal account).


Don't forget to check my new How To Tutorial eBooks (PDF format):

to see a lot of fully commented examples that help you use the Perl statements and the Perl buit-in functions in your scripts.






NEW!!!

Do you want more information about the basic Perl topics?

Check my new "Perl How To" Tutorial eBooks page where I'll answer the most frequent questions regarding some topics :


Perl How To Tutorial eBooks


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
        Array Functions
    Functions in alphabetical order
        chomp
        chop
        chr
        crypt
        defined
        grep
        hex
        index
        join
        lc
        lcfirst
        length
        map
        oct
        ord
        pack
        pop
        push
        qw
        reverse
        rindex
        scalar
        shift
        sort
        splice
        split
        substr
        uc
        undef
        unshift

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!


footer for perl shift page