Perl push Function

These sites are FOR SALE: miscperlinfo.com, mpihowto.com!
If you are interested, please use my Contact page.




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.


Click Below to See the Best

Perl How-to Snippet Collection

and Save Hours of Surfing on Internet!


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 () {
  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).

Please click here to download the Perl push 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 push 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.

Some of the following exercises use text files, to test your scripts you need to create by yourself these files, using your favorite editor.

1. You have a text file that contains the elements of a matrix with 3 rows and 4 columns, delimitated by whitespace:
112    02 34 45
29 22 89 0123
11   356   -72 321
Read this file using a while loop and use the push function to create an array of arrays from it. Finally, print the array of arrays. Your output must be something like that:
112 02 34 45
29 22 89 0123
11 356 -72 321
2. You have a matrix represented as an array of arrays (@AoA). Use the push function to append a column (@column) to 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:
12 2 34 1
29 22 89 2
11 35 -5 3
3. You have a matrix represented as an array of arrays (@AoA). Use the push function to append a raw (@raw) to this matrix. You can use these arrays:
my @AoA = (
            [12, 02, 34],
            [29, 22, 89],
            [11, 35, -5],
          );
my @raw = (1, 2, 3);
Finally, print the @AoA array, the output is:
12 2 34
29 22 89
11 35 -5
1 2 3
4. Given the following text file:
John,Silva,2520
Mary,Brown,3200
Anne,Williams,5280
use push function to create an array with the records of the file. Each element of this array is a reference to an inner array that has as elements the items from the file raw. Finally, print your array, you need to get something like the output below:
John Silva 2520
Mary Brown 3200
Anne Williams 5280
5. Use push to add a new element (name = 'Mary', age= '50') to the following array of hashes:
my @AoH = ( 
  { name => 'John', age => '21' },
  { name => 'Paul', age => '35' },  
);
Print the resulting @AoH as:
John is 21 years old.
Paul is 35 years old.
Mary is 50 years old.
6. Give an example about how to use push to append a list of elements to a specific inner array of a hash of arrays. Use the following hash of arrays:
my %HoA = ( 
  a => [qw(abacus ant antique asset)],
  b => [qw(basket bed bird)],  
  c => [qw(car cinema)],
);
and append the list of elements ('ball', 'belly') to the inner array referenced by the value corresponding to the 'b' key. Print the hash of arrays as follows:
c => car cinema
a => abacus ant antique asset
b => basket bed bird ball belly
7. Given the following array:
my @array = qw(1 2 3 4 5 6 7 3 4 5 6 7 8 9);
extract the unique elements of the array into another one and print this new array.


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 (more)
        q
        qq
        qw
        reverse
        rindex
        scalar
        shift
        sort
        splice
        split
        sprintf
        substr
        tr
        uc
        ucfirst
        undef
        unpack
        unshift
        values

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!