Perl Monk, Perl Meditation PerlMonks

### Simple stack implementation

by quidity (Pilgrim)
 on Nov 17, 2000 at 23:22 UTC 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;

sub TIESCALAR {
\$_[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)

Create A New User
Node Status?
node history
Node Type: snippet [id://42268]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (4)
As of 2018-04-27 07:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My travels bear the most uncanny semblance to ...

Results (97 votes). Check out past polls.

Notices?