eWebProgrammer eweb  

Perl Variables  «Prev  Next»
Lesson 10Using an array as a stack
ObjectivePrompt String, push onto array
Program that prompts for string, pushes it onto an array.
Using an array as a stack in Perl.
The array structure in Perl can be used as more than just an accumulation of scalar values. It is also used as a stack, which is often a very convenient data abstraction.

Perl Stack Array

Diagram of a stack
Diagram of a stack
Visualize a data stack as being like a stack of blocks. The block at the bottom of the stack is array element 0, and the block at the top of the stack is the highest-numbered element in the array. A stack is sometimes called a LIFO (last-in/first-out) data structure, because the most recently added data is always the first data retrieved.
The push function
The Perl function push is used to push a new value onto an array. In the following example, the latest Academy Award-winner is added to the list:
#!/usr/bin/perl -w

@bestpix = ( "Ordinary People",
"Chariots of Fire", "Gandhi",
"Terms of Endearment", "Amadeus",
"Out of Africa", "Platoon",
"The Last Emperor", "Rain Man",
"Driving Miss Daisy",
"Dances with Wolves",
"The Silence of the Lambs", "Unforgiven",
"Schindler's List", "Forrest Gump",
"Braveheart", "The English Patient" ); 

>push @bestpix, "Titanic";
print join("\n", @bestpix);
print "\n";

Stack Push Function
The pop function
When you pop an element from the stack, it is removed from the top in a last-in, first-out (LIFO) manner.
You can use Perl's pop function to remove elements from the stack in reverse order, like this:
while (@bestpix) {
  $pic = pop @bestpix; 
  print "$pic\n";
Stack Pop Function
There are a few other lesser-used functions that work specifically on arrays:
  1. shift and unshift
  2. Perl Splice Function
Push Function - Exercise
Click the Exercise link below to write a program that uses the push function.
  Push Function Exercise