My question in Perl:
Write a Perl Script with a subroutine that accepts a list of values and returns the largest,smallest and average values to the calling program.
#!/usr/bin/perl
sub large_and_small {
my (@numbers);
@numbers = @_;
my ($small, $large);
$large = $numbers[0];
$small = $numbers[0];
foreach my $i (@numbers) {
if ($i > $large) {
$large = $i;
}
elsif ($i < $small) {
$small = $i;
}
}
return ($small, $large);
}
sub avg {
my ($avg);
my ($total);
foreach (@test_array) {
$total += $_;
}
$avg = $total/scalar @test_array;
return $avg;
}
my (@test_array, @ret);
@test_array = (15, 5, 7, 3, 9, 1, 20,1 3, 9, 8, 15, 16, 2, 6, 12, 90);
@ret = large_and_small(@test_array);
print "The Largest value is ", $ret[1], "\n";
print "The Smallest value is ", $ret[0], "\n";
print "The Average value is", avg(@test_array), "\n";
The Output I am getting is:
The Largest value is 90
The Smallest value is 1
Illegal division by zero at /tmp/135044395416028.pl line 59.
Where am I going wrong in the script? Please help.Thanks in advance
Best Answer
I advice you use core module:
List::Util
, it has all functions, that you implemented as min, max, sum.