... i can't figure out how to clear the foreach loop for every new set of data it uploads from a file.
The push built-in only adds elements to the end of an array (as you have discovered). Somewhere near the top of the main
while (1) { ... }
loop and before reading the file into the array, add a
@array = ();
statement to clear the array.
Better yet, IMHO: Because the @array array is not used outside the while-loop in this code, only declare the array at the point at which it is needed. (The same applies to the $average scalar.) Something like
or more simply, forget the while-loop and justmy @array; while (my $data = <FH>) { push @array, $data; }
Combined with the change to the average() function that pryrt suggested, things should go more smoothly.my @array = <FH>;
Update: Note that in the
loop of the OPed code, the elsif ($average = $_) { ... } clause of the ladder of if-tests does not work as I expect you expect. The $average = $_ expression assigns to $average and does not test it.foreach (@array) { chomp; if ($average > $_) { print "$_\t is below average.\n"; } elsif ($average < $_) { print "$_\t is above average.\n"; } elsif ($average = $_) { print "$_\t is equal to average.\n"; } }
I assume you meant $average == $_ as the test, although at that point the variables can only be equal (i.e., neither is greater nor less than the other), so a plainc:\@Work\Perl\monks>perl -wMstrict -le "my @array = (-2, -1, 0, 1, 2); my $average = 0; ;; foreach (@array) { if ($average > $_) { print qq{$_\t is below average.}; } elsif ($average < $_) { print qq{$_\t is above average.}; } elsif ($average = $_) { print qq{$_\t is equal to average.}; } } " -2 is below average. -1 is below average. 1 is above average. 2 is above average.
And another thing...
The code posted by pryrt for the average() subroutine returns 0 for an empty list of numbers passed to the function.
I think I would have elected to return undef or perhaps throw an exception, but this behavior is the option of the programmer. However, one should be aware of it.c:\@Work\Perl\monks>perl -wMstrict -le "print average(); ;; sub average { if (@_) { my @temp = @_; my $sum = 0; foreach (@temp) { $sum = $sum + $_; } return $sum/@temp; } } " 0
Give a man a fish: <%-{-{-{-<
In reply to Re: resetting a foreach loop!
by AnomalousMonk
in thread resetting a foreach loop!
by lunette
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |