in reply to Circular buffer
In Perl, a Perl array can be used to implement a FIFO buffer. A Perl array is different from arrays in C or other programming language's ideas of arrays in that it can change size. So to implement a FIFO queue in Perl, just push new entries onto the bottom of the Perl array and shift out "oldest" entries from the top. The size of the Perl array (and the indicies) will adjust themselves without you having to "move" anything. For the idea, this code is untested, but I figure should work...
The Perl array also can implement essentially the equivalent of a 'C' doubly linked list. In Perl, this is an array of pointer to hash (an Array of Hash). In C this might be an array of struct and you couldn't change it without a lot of hassle or a linked list where you have to adjust many forward and backward pointers. But in Perl you can use splice() to insert or delete something from the middle of the array (or linked list 'C' analog)! WOW!my @fifo; my $MAX_FIFO = 53; #max size is optional sub add_entry { die "Cicular buffer overflow\n" if (@fifo >= $MAX_FIFO); my $entry = shift; #well, $_[0] is ok for syntax too #but I think this is more clear #these simple assignment statements are # not "expensive" push @fifo, $entry; } sub get_entry { return (shift @fifo); }
get_entry() above could be modified to "die" if the @fifo is empty. There are lots of other possibilities. I advise the OP to study the Perl functions: push, pop, shift, unshift and splice.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Circular buffer
by ikegami (Patriarch) on Mar 21, 2011 at 03:11 UTC | |
by Marshall (Canon) on Mar 21, 2011 at 05:56 UTC | |
by ikegami (Patriarch) on Mar 21, 2011 at 15:52 UTC |