Tweet

Using the Perl push() function

Introduction

You can use the push function to add new elements to the end of an array.

Example 1. Adding an item onto an array

You can use push to push an element onto the end of an array:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my @planets = qw(mercury venus earth mars);

    print "@planets\n";

    push (@planets, 'jupiter');

    print "@planets\n";

    exit 0;

This program produces the following output:

    mercury venus earth mars
    mercury venus earth mars jupiter

You can see that 'jupiter' is now on the end of our @planets array.

The push function returns the number of elements in the array after the new value(s) have been appended. If we wanted to see how many planets were in the modified @planets array, we could change our code as follows:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my @planets = qw(mercury venus earth mars);

    print "@planets\n";

    my $number_of_planets = push (@planets, 'jupiter');

    print "@planets\n";

    print "The number of planets is: $number_of_planets\n";

    exit 0;

The output is now:

    mercury venus earth mars
    mercury venus earth mars jupiter
    The number of planets is: 5

Example 2. Joining two arrays together

You can also use push to append an array onto the end of another array:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my @planets = qw(mercury venus earth mars);

    my @outer_planets = qw(jupiter saturn uranus neptune pluto);

    print "@planets\n";

    push (@planets, @outer_planets);

    print "@planets\n";

    exit 0;

As the following output demonstrates, the @outer_planets array has been added to the end of the @planets array:

    mercury venus earth mars
    mercury venus earth mars jupiter saturn uranus neptune pluto

Example 3. Adding to an array reference

You can use push to append elements onto the end of a reference to an array, but you must dereference it first:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my @planets = qw(mercury venus earth mars);

    my $planets_ref = \@planets;

    push ( @{ $planets_ref }, qw(jupiter saturn uranus neptune pluto));

    # Could also be written as:
    # push ( @$planets_ref, qw(jupiter saturn uranus neptune pluto));

    print "@{ $planets_ref }\n";

    # Could also be written as:
    # print "@$planets_ref\n";

    exit 0;

This produces the following output:

    mercury venus earth mars jupiter saturn uranus neptune pluto

See also

  perldoc -f push
  perldoc -f pop
  perldoc -f shift
  perldoc -f unshift
  perldoc -q "difference between a list and an array"
[Top]