New Ways with Arrays

Previous Table of Contents Next

New Ways with Arrays

In the following section, we will discuss a set of array functions that make several powerful data structures possible in Perl.

A List as a Stack

Until now, lists (and arrays) have been presented as linear arrangements of data with indexes that make it possible to access each element, as shown here:

Use your imagination for a moment and imagine the array elements piled up vertically with the element having the highest index at the top, as shown here:

Notice that there are no index numbers in this figure. The reason is that the functions we will discuss here are concerned with only the top and the bottom of the array, not with anything in the middle. In computer terminology, this list is called a stack. Stacks are useful for accumulating tasks that you want processed in order. A good example is a game of Klondike solitaire (like the Solitaire game often installed with Windows). Each of the seven piles of cards represents a stack. Initially, cards are placed onto the stack face down. As they are needed, they are turned over and removed from the top of the stack, or additional cards can be placed on top of the newly turned-over cards, but cards cannot be removed or inserted in the middle of the stack or at the bottom.

Stacks in Perl are (usually) implemented with arrays. To place items on top of a stack, you use the push function. To remove from the top of the stack, you use the pop function.

A stack implemented as a Perl array can also be modified from the bottom, like dealing from the bottom of the deck of cards. The shift function removes elements from the bottom, and unshift adds elements to the bottom of the stack. All four operations are shown here:

Previous Table of Contents Next
© 2000- NIV