I've made it to Chapter four, thus far (Subroutines)
I'm on an exercise that I can kind of half-way get, but I'm not sure how to complete the rest of it.
The Exercise is as follows:
Extra credit exercise: Write a subroutine, called above_average, that takes a list of numbers and returns the ones that are above average(mean). (Hint: Make another subroutine that calculates the average by dividing the total by the number of items.) Try your subroutine(s) in this test program:
- Code: Select all
my @fred = above_average(1..10);
print "\@fred is @fred\n";
print "(Should be 6, 7, 8, 9, 10)\n"
my @barney = above_average(100, 1..10);
print "\@barney is @barney\n";
print "(Should be just 100)\n";
My code is as follows:
- Code: Select all
my @fred = above_average(1..10);
print "\@fred is @fred\n";
print "(Should be 6 7 8 9 10)\n";
my @barney = above_average(100, 1..10);
print "\@barney is @barney\n";
print "(Should be just 100)\n";
sub above_average {
my $sum;
my $average;
my $count = @_;
foreach (@_) {
$sum += $_;
$average = $sum/$count
}
foreach my $element (@_) {
if ($element > $average) {
push @list, $element;
}
}
@list;
}
But it returns 6,7,8,9,10 for both @fred and @barney, where @barney should only return 100. How do I edit my code to get it to return only 100?
Thanks so much for your constructive help.