Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

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;

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]};
  }
}
Comment on Simple stack implementation
Download Code
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)

Back to Snippets Section

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (9)
As of 2014-11-28 20:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (200 votes), past polls