by

Calculating the Average of an Array in Perl

The code below demonstrates a short Perl function that takes an array as an argument and returns the average of this array.

#!/usr/bin/perl

sub average {
my @array = @_; # save the array passed to this function
my $sum; # create a variable to hold the sum of the array's values
foreach (@array) { $sum += $_; } # add each element of the array 
# to the sum
return $sum/@array; # divide sum by the number of elements in the
# array to find the mean
}

@dataArray = (1, 2, 3, 4, 5, 6, 7, 8, 9);
$avgOfArray = average(@dataArray);
# here the average will be 5

Leave a Reply

Your email address will not be published.