http://www.perlmonks.org?node_id=1035026


in reply to Duplicate Results from Subroutine

To fix this specific problem, you need to localize @cands in abv() rather than up at the top of the script.

sub abv { # Move from top of the script down to here my @cands = (); foreach my $cand (@numlist) { if ($cand > $numlist_avg) { push(@cands, $cand); } } return @cands; }

Each time you call abv(), it remembers @cands from the last time you call it, and returns the duplicate values as well as the new ones.

It's a good idea to localize your variables to the smallest possible block. Declare them in the subroutine that's using them.

You're also assuming that $numlist_avg has already been determined. If you tried calling abv() before setting $numlist_avg, you might wind up with a hard-to-trace error.

While we're at it, you're passing @numlist to the subroutine as an argument, but not actually using that argument. If you called abv(1,2,3) it would still go over @numlist to get the result. So, instead, you should do:

sub abv { my (@numlist_args) = @_; my @cands = (); my $avg = avg(@numlist_args); foreach my $cand (@numlist_args) { if ($cand > $avg) { push(@cands, $cand); } } return @cands; }
Good luck!

stephen