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

Perl push Function



NEW!!!

Check my new resource:    Perl How To Tutorial eBooks



Perl push function is used to append a list to the right side of an array. It returns the number of elements of the array after pushing the elements. This function is similar with unshift that inserts a list of elements in front of an array and is the opposite of the pop/shift function that removes the last/first element of an array.

push and pop functions can manipulate an array like a stack. On the other side, both push and shift functions can be used to treat an array as a queue.

This short free tutorial will give you some examples about how you can use Perl push function in your script applications. But to begin with, let’s see its syntax form:

push (ARRAY, LIST)

The first argument of Perl push function will tell you which array to operate on, and the second lets you specify the elements to be added to the array. The parentheses are optional. It returns the number of the elements after appending the elements from the list. Now here are a few lines of code to see some examples.

Appending a list to an array or one array to another


The next example will join an array with a list, using the push function:

#!/usr/bin/perl

use strict;
use warnings;

my @array = (1, 2, 3, 4);
my $size = push (@array, (5, 6, 7));
# or my $size = push (@array, 5, 6, 7);
# or my $size = push @array, (5, 6, 7);
# or my $size = push @array, 5, 6, 7;

print "\$size = $size, \@array = @array\n";

The output is as follows:

$size = 7, @array = 1 2 3 4 5 6 7

In the above example, we could create an array from our list at first and then concatenate both the arrays.

Or, if we have a reference to an array, because Perl push function needs an array and not a reference to an array, we must dereference the reference in order to use it.

See the next short snippet code that illustrates the two short notes from above:

#!/usr/bin/perl

use strict;
use warnings;

my @array = (1, 2, 3, 4);
my @newArray = (5, 6, 7);
push(@array, @newArray);
print "\@array = @array\n";
# it displays @array = 1 2 3 4 5 6 7

# empty the array 
@array = ();
# define a reference for @newArray
my $ref = \@newArray;
# dereference it
push(@array, @$ref);
print "\@array = @array\n";
# it displays @array = 5 6 7

Another note that I want to make is that if you try to append non-existent elements from an array to another one, the initial array will grow as needed, even though the elements to append do not exist. Consider the next snippet code:

#!/usr/bin/perl

use strict;
use warnings;

my @array = (1, 2, 3, 4);
my @newArray = (5, 6, 7);

my $size = push(@array, @newArray[1..4], 9);
print "\$size = $size, \@array = @array\n";

and the output after running this code from a command line prompter:

Use of uninitialized value in join or string at 1.pl line 10.
Use of uninitialized value in join or string at 1.pl line 10.
$size = 9, @array = 1 2 3 4 6 7   9

As you can see, after pushing, the number of the elements of the array is 9 (= 4 + 4 +1), there are two elements not initialized because in @newArray[1..4] the elements @newArray[3], @newArray[4] do not exist. (Well, 1.pl is the name of my script file).

If you need to insert the elements of an array within another, you can use the splice function.

Concatenating two arrays by alternating their elements


In the following example, we'll use Perl push function to concatenate two arrays by alternating their elements. We suppose that both arrays have the same number of elements.

#!/usr/bin/perl

use strict;
use warnings;

my @array1 = ('one', 'two', 'three', 'four') ;
my @array2 = ('1: ', '2: ', '3: ', '4: ') ; 
my @array3 = ();

push @array3, $array2[$_] . $array1[$_] foreach 0..$#array1;

print "@array3\n";

the output after running this sample code is as follows:

1: one 2: two 3: three 4: four

Please note the concatenating operator (.) and $#array1 notation for the number of elements of @array1.

Using Perl push function to create an array from a file


Sometimes the array you want to build is big enough and is stored in a file. In order to create the array, you need to read the file lines one by one and store them in the array. You can use Perl push function to do this, as in the following example:

#!/usr/bin/perl

use strict;
use warnings;

# empty and initialize the array
my @lines = ();
open(FILE, "< file.txt") 
     or die "Couldn't read from file.txt: $!\n";
while (<FILE>) {
  chomp;
  # chomp the trailing newline
  push(@lines, $_);
  # append the line onto the end of the array
}

Using arrays as stacks


We can simply treat an array like a stack, by appending or removing elements onto the end of the array. We use Perl push function to append a list of elements at the end of an array and Perl pop function to remove the rightmost element of the array. The push & pop functions treat the "right hand side" of the array as the top of the stack. Have a look at the following snippet code:

#!/usr/bin/perl

use strict;
use warnings;

# initialize an array with some operators
my @stack = qw(+ - * /);
# remove the first element
pop @stack;
print "@stack\n";
# stack is now (+ - *) 
# append some elements onto the end of the stack
push(@stack, '/','%');
print "@stack\n";
# stack is now (+ - * / %)  

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

Using arrays as queues


Using the push & shift functions, 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
# append a few elements at the end
push (@queue, 'five', 'six');
# remove the first element
shift @queue;
print "@queue\n";
# it displays two three four five six

Using Perl push function to implement a simple circular list


There is not a heavy task to implement a simple circular list. For this you may use push and shift (or unshift and pop). 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 take off and return the leftmost element of the circular list, i.e. 'a', and the push function will append this element onto the end of the circular list. The elements of the circular list will move from right to left.

Using Perl push with array references


One way to get a reference to an array is to prepend the array with \ (backslash) sign. To dereference any array reference, you need to precede it with an at sign (@). Here is an example about how to use Perl push function with an array reference:

#!/usr/bin/perl

use strict;
use warnings;

# initialize an array
my @array = (1, 2, 3, 4);
# get a reference to it
my $ref = \@array;
# apply push (append a few elements)
push(@$ref, 5, 6, 7);
# or push @{$ref}, 5, 6, 7;

# print the array using the reference
print "@{$ref}\n";
# it displays 1 2 3 4 5 6 7

As you can notice, we need to dereference the reference by using the notation @$ref or @{$ref} in order to call Perl push function (it has an array as its first argument and not a reference to an array).




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
        oct
        ord
        pack
        pop
        push
        reverse
        rindex
        shift
        split
        substr
        uc
        undef
        unshift

return from Perl push 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 push page