- 论坛徽章:
- 145
|
回复 1# palladiosh
How about this way ...
$ perl avg.pl
Name:John, Average:84
Name:Mary, Average:85
$ cat avg.pl
use strict;
use warnings;
my %hScore = ();
while(<DATA>){
chomp;
my($sName, $sNo, $sScore) = split /,/;
if (exists $hScore{$sName}){
# this student is already in the hash:
my $rhName = $hScore{$sName};
$rhName->{'total'} += $sScore;
$rhName->{'subject'}++;
$rhName->{'average'} = $rhName->{'total'} / $rhName->{'subject'};
}
else{
# this is a new student:
$hScore{$sName}->{'total'} = $sScore;
$hScore{$sName}->{'subject'} = 1;
$hScore{$sName}->{'average'} = $sScore;
}
}
foreach my $sName (keys %hScore){
print "Name:", $sName, ", Average:", $hScore{$sName}->{'average'}, "\n";
}
__DATA__
Mary,math,82
Mary,eng,88
John,math,84
|
|