Beefy Boxes and Bandwidth Generously Provided by pair Networks vroom
We don't bite newbies here... much
 
PerlMonks  

Re^2: Circular buffer

by mellon85 (Monk)
on Mar 20, 2011 at 17:11 UTC ( #894360=note: print w/ replies, xml ) Need Help??


in reply to Re: Circular buffer
in thread Circular buffer

I don't like leaving the $pointer variable grow indefinitely.
This code is equivalent, but keeps $pointer in [0,@buffer). In fact, just gets the remainder after each $pointer change

my @buffer = (0) x 5; my $pointer = 0; for (0..30) { print "old value: ", $buffer[$pointer], "\n"; print "new value: $_\n"; $buffer[$pointer] = $_; $pointer = (++$pointer) % @buffer; }


Comment on Re^2: Circular buffer
Download Code
Re^3: Circular buffer
by moritz (Cardinal) on Mar 20, 2011 at 18:53 UTC

    I usually avoid code like $pointer = (++$pointer) % @buffer; where the same variable is modified twice within the same expression. It means that the outcome depends on the order of evaluation, which isn't defined in all cases (it is in the case of assignment though).

    Instead I'd just write $pointer = (1 + $pointer) % @buffer.

Re^3: Circular buffer
by repellent (Priest) on Mar 20, 2011 at 19:08 UTC
    No $pointer. @buffer always ordered last to most recent.
    my @buffer = (0) x 5; for (0..30) { print "old value: ", $buffer[0], "\n"; print "new value: $_\n"; shift @buffer; push @buffer, $_; }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2014-04-25 02:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (579 votes), past polls