note
frozenwithjoy
If I were going to do this and wanted to have it expandable, I'd probably plan to make a hash like this (you can simplify it if you don't care about keeping track of student IDs and never have students with the same names):
<c>
my %records = (
12445 => {
name => 'Jack',
scores => [ 45, 10 ],
},
234254 => {
name => 'Jill',
scores => [ 45, 10 ],
},
);
</c>
<p>If the data are consistently in the format shown, the following will make the hash (it can accept scores w/ decimals). It then calculates and reports the mean score.</p>
<c>
#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
use List::Util 'sum';
my %records;
while ( my $name = <DATA> ) {
my ($id) = <DATA> =~ /(\d+)$/;
my ($score) = <DATA> =~ /(\d+\.?\d*)$/;
<DATA>;
chomp( $name, $id, $score );
$records{$id}{name} = $name;
push @{ $records{$id}{scores} }, $score;
}
for ( sort { $a <=> $b } keys %records ) {
my $name = $records{$_}{name};
my @scores = @{ $records{$_}{scores} };
my $mean = sum(@scores) / @scores;
say "$name ($_) has an average score of $mean";
}
__DATA__
Jack
Student ID - 12445
Math Score - 45
Jill
Student ID - 234254
Math Score - 90
Jack
Student ID -12445
Math Score2 - 33
Jill
Student ID - 234254
Math Score2 - 10
</c>
<p>
OUTPUT:
</p>
<c>
Jack (12445) has an average score of 39
Jill (234254) has an average score of 50
</c>
1054374
1054374