in reply to Circular buffer instead of shift/push

Here's much the same thing, but using a closure. I'm sure this will slow down the process but can improve the usage of it by seperating the buffer from the rest of the code, and allowing easy reuse - and multiple buffers if desired - without needing to intersperse your code in amoungst other processing. It's a matter of tradeoffs, but I'm not sure on how much slower it will be.
my $buf = make_buf(3); &$buf('hi'); &$buf('moo'); print join(' ', &$buf) . "\n"; # 'hi moo' $buf->('foo','no'); print join(' ', $buf->()) . "\n"; # 'moo foo no' sub make_buf { my $size = shift || 3; my @buf; my $pos = -1; my $last = $size - 1; return sub { if (@_) { while (@_) { $buf[ $pos==$last ? $pos=0 : ++$pos ] = shift + } } elsif (wantarray) { return ($#buf==$last ? @buf[ $pos+1 .. $last, 0 .. $pos ] +: @buf); } else { warn "Call with an argument or in list context"; return +; } } }

Replies are listed 'Best First'.
Re: Re: Circular buffer instead of shift/push
by fundflow (Chaplain) on Jan 12, 2001 at 20:32 UTC
    Nice. Note that you can change the actual operations inside the sub to those suggested above. Removing the trinary operator ?: will definitly help speed.