Perl array push and pop syntax and examples

Perl array push pop FAQ: How do I push elements onto a Perl array, and how do I pop element off a Perl array? (Or, What is the Perl push and pop syntax?)

I really like the Perl push (and Perl pop) syntax. The push function makes adding elements to a Perl array very easy, and the pop function also makes a Perl array work a lot like a stack.

Perl push syntax example

The Perl push function lets you easily add elements to a Perl array. You "push" them onto the array. (If you've ever seen any assembly code, you've seen "push" before.) Here's a simple (but complete) example of the push syntax:

# declare a perl array
my @pizzas;

# push a few strings onto the array
push @pizzas, 'cheese';
push @pizzas, 'veggie';
push @pizzas, 'pepperoni';

# print the array
print "@pizzas\n";

This Perl push example results in the following output:

cheese veggie pepperoni

As you can see, the push syntax is easy to read, and easy to use. It makes working with an array in Perl just as easy as working with something like a linked list in Java.

A Perl pop syntax example

The Perl pop function lets you "pop" elements off of a Perl array. When you pop an element off an array, you are actually removing the element from the array.

This Perl pop function really reminds me of a stack, because this is typically what you do with a stack: push elements onto the stack, and then pop them off.

Here's a simple script that shows how the pop function works:

# create our perl array with the perl push syntax
my @pizzas;
push @pizzas, 'cheese';
push @pizzas, 'veggie';
push @pizzas, 'pepperoni';

# pop the first element off the array
$foo = pop @pizzas;
print "item = '$foo'\n";
print "remaining elements: @pizzas\n";

# pop the second element off the array
$foo = pop @pizzas;
print "\nitem = '$foo'\n";
print "remaining elements: @pizzas\n";

# pop the last element off the array
$foo = pop @pizzas;
print "\nitem = '$foo'\n";
print "remaining elements: @pizzas\n";

And here's the output you'll get when you run this Perl script:

item = 'pepperoni'
remaining elements: cheese veggie

item = 'veggie'
remaining elements: cheese

item = 'cheese'
remaining elements: 

Summary: Perl array ‘push’ and ‘pop’ examples

I hope these Perl array push and pop examples have been helpful. I find that when I work with Perl a lot, this pop and push syntax is fairly easy to remember and also easy to read.