What is the difference between push and unshift in Perl?

You really should be using use strict; and use warnings; in your code. Having them activated will allow you to identify errors in your code.

Change all instances of the following:

foreach $name (@names) -> for my $i (@names) as you don't do anything with the elements in the @names array.

@numbers[i] -> $numbers[$i] as this is where you've made a not uncommon mistake of using an array slice rather than referring to an array element.

This is not C. Every 'variable' has to have a sigil ($, @, %, &, etc.) in front of it. That i should really be $i.


As for the difference between push and shift, the documentation explains:

perldoc -f push:

push ARRAY,LIST

Treats ARRAY as a stack, and pushes the values of LIST onto the end of ARRAY. The length of ARRAY increases by the length of LIST. ... Returns the number of elements in the array following the completed "push".

perldoc -f unshift:

unshift ARRAY,LIST

Does the opposite of a shift. Or the opposite of a push, depending on how you look at it. Prepends list to the front of the array, and returns the new number of elements in the array.


To put it ASCII-matically...

        +---------+           +-----------+        +---------+ 
<-----  | ITEM(S) |  ----->   | (@) ARRAY | <----- | ITEM(S) | ----->
 shift  +---------+  unshift  +-----------+  push  +---------+   pop
                              ^           ^
                              FRONT       END

unshift is used to add a value or values onto the beginning of an array:

Does the opposite of a shift. Or the opposite of a push, depending on how you look at it.

The new values then become the first elements in the array.

push adds elements to the end of an array:

Treats ARRAY as a stack, and pushes the values of LIST onto the end of ARRAY.


This should really be a comment but it is too long for a comment box, so here it is.

If you want to illustrate the difference between unshift and push, the following would suffice:

#!/usr/bin/perl

use strict; use warnings;

my @x;

push @x, $_ for 1 .. 3;

my @y;

unshift @y, $_ for 1 .. 3;

print "\@x = @x\n\@y = @y\n";

Output:

@x = 1 2 3
@y = 3 2 1

Note use strict; protects you against many programmer errors and use warnings; warns you when you use constructs of dubious value. At your level, neither is optional.

Tags:

Perl