Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Simple stack implementation

by quidity (Pilgrim)
on Nov 17, 2000 at 23:22 UTC ( #42268=snippet: print w/replies, xml ) Need Help??
Description: This is a quick way of using a scalar to construct a stack, it can be both fifo or filo. It is also a nice example of the fun that can be had when tie 'ing variables.

It is, of course, easier to do this by just using the array, but not half as much fun...
tie $foo, Stack, 'fifo' or die "Could not tie";

$foo = $_ for (1..10);

print while (defined($_ = $foo));

package Stack;

  $_[1] =~ /[fl]i[fl]o/i &&  return bless [$_[1],[]], $_[0];
sub STORE {
  push @{$_[0]->[1]}, $_[1];
sub FETCH {
  return undef unless @{$_[0]->[1]};
  if ($_[0]->[0] =~ /(f|l)i\1o/i) {
    return shift @{$_[0]->[1]};
  else {
    return pop @{$_[0]->[1]};
Replies are listed 'Best First'.
Re: Simple stack implementation
by Adam (Vicar) on Nov 18, 2000 at 00:24 UTC
    That's all well and good, if you are trying to learn about stacks.

    But if you are trying to make a stack for actuall use in Perl, just use an array. Then you get push and pop free!, plus arrays are like double ended queues, so you get shift and unshift.
    See Shift, Pop, Unshift and Push with Impunity! for some good insight into this.

      He did use an array.

        Yes, but the over-head of tieing it to a scalar is excessive.
Re: Simple stack implementation
by extremely (Priest) on Nov 18, 2000 at 13:46 UTC
    Cute, simple and exposes a feature in an interesting way. That's an easy ++ in my book.

    $you = new YOU;
    honk() if $you->love(perl)

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: snippet [id://42268]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2021-10-26 10:00 GMT
Find Nodes?
    Voting Booth?
    My first memorable Perl project was:

    Results (90 votes). Check out past polls.