Reputation: 19
I am looking to return an average of the hash values (per key) below (grades.txt)
Melotti, Suzanne: 100 100 95 95 92 87
Wayne, Bruce: 85 85 85 75 75 75
Stark, Tony: 92 92 75 79 91 87
Odinson, Thor: 23 12 10 42 50 64
Kane, Kathy: 100 100 100 100 95 95
Rogers, Steven: 92 91 91 90 87 84
Murdock, Matthew: 100 100 100 99 99 98
VonDoom, Victor: 75 75 72 73 74 80
Queen, Olvider: 92 83 74 65 100 66
Hall, Carter: 23 12 10 42 50 64
Xavier, Charles: 100 100 95 95 92 87
My subroutine looks like this so far:
$grade_file = "grades.txt";
open FILE, "<", $grade_file;
sub avg {
while (<$FILE>){
foreach $line ($grade_file){
# some code
return $total
}
}
}
Upvotes: 0
Views: 330
Reputation: 6818
Calculation of average grade without external modules
use strict;
use warnings;
while(<DATA>) {
my($k,$d) = split ':';
printf "%20s : %.2f\n", $k, average($d);
}
sub average {
my $data = shift;
my(@data,$sum);
@data = split ' ', $data;
$sum += $_ for @data;
return $sum/@data;
}
__DATA__
Melotti, Suzanne: 100 100 95 95 92 87
Wayne, Bruce: 85 85 85 75 75 75
Stark, Tony: 92 92 75 79 91 87
Odinson, Thor: 23 12 10 42 50 64
Kane, Kathy: 100 100 100 100 95 95
Rogers, Steven: 92 91 91 90 87 84
Murdock, Matthew: 100 100 100 99 99 98
VonDoom, Victor: 75 75 72 73 74 80
Queen, Olvider: 92 83 74 65 100 66
Hall, Carter: 23 12 10 42 50 64
Xavier, Charles: 100 100 95 95 92 87
Output
Melotti, Suzanne : 94.83
Wayne, Bruce : 80.00
Stark, Tony : 86.00
Odinson, Thor : 33.50
Kane, Kathy : 98.33
Rogers, Steven : 89.17
Murdock, Matthew : 99.33
VonDoom, Victor : 74.83
Queen, Olvider : 80.00
Hall, Carter : 33.50
Xavier, Charles : 94.83
Upvotes: 3
Reputation: 242423
Use sum
from List::Util. To get the number of elements, just use an array in scalar context.
#!/usr/bin/perl
use strict;
use warnings;
use feature qw{ say };
use List::Util qw{ sum };
while (<>) {
my ($name, $points) = split /: /;
my @points = split ' ', $points;
say $name, ': ', sum(@points) / @points;
}
Upvotes: 6