Perl Largest,Smallest,Average of numbers using Subroutines

perl

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.

#!/usr/bin/perl

use strict;
use List::Util qw(min max sum);

my @test_array = (15, 5, 7, 3, 9, 1, 20, 13, 9, 8, 15, 16, 2, 6, 12, 90);
my $min = min(@test_array);
my $max = max(@test_array);
my $avg = scalar @test_array
        ? (sum(@test_array) / (scalar @test_array))
        : 0;

print "The Largest value is ", $max, "\n";
print "The Smallest value is ", $min, "\n";
print "The Average value is ", $avg, "\n";
Related Topic