|
Posted by sln on June 6, 2008, 1:17 pm
Please log in for more thread options
>This newbie need some technical information:
>
>....after the creation of an array of (just for grins..) 10 integers read in
>from (more grins....) the serial port, what is the proper way to maintain the
>array to ONLY 10 values?
>
>I want to first create an array: .... $#Test = sprintf (%d, 100/10)
>
>now, as data comes in via the serial port (I keeping everything in decimal) I
>first want to "shift" the data: shift (@Test)
>
>and then push the new data: push (@Test, newdata).
>
>After the new data is inserted, I perform calculations (averages, etc) and then
>move on..... until the next loop when the shift and push are executed again.
>
>Because I am not using the shifted data, does the shift statement just pull the
>data and throw it away? .... and is this a safe way to rotate the data within
>the array?
>
>Tnx, in advance....
>Hobart
You could do a little more fancy ring buffer:
====================
use strict;
use warnings;
my $head = 0;
my $tail = 0;
my $bufsize = 10;
my @ringbuffer = ();
my ($i, $val);
for ($i = 0; $i < 26; $i++)
{
if (!AddHead ( $i )) {
print "Buffer will overflow, take some off first\n";
while (RemoveTail( $val )) {
print "val= $val\n";
}
$i--;
}
}
print "Cleaning out buffer\n";
while (RemoveTail( $val )) {
print "val= $val\n";
}
sub AddHead
{
my $tmp = $head+1;
$tmp = 0 if ($tmp > $bufsize);
return 0 if ($tmp == $tail);
$head = $tmp;
$ringbuffer[$head] = shift;
return 1;
}
sub RemoveTail
{
my $refval = shift;
die "RemoveTail(): Parameter required.\n" if(!defined($refval));
return 0 if ($head == $tail);
$tail++;
$tail = 0 if ($tail > $bufsize);
$$refval = $ringbuffer[$tail];
return 1;
}
===========
sln
|