An Average Example
Suppose you’ve been teaching a Perl class, and you’re trying to figure out how to grade your students. You have a set of exam scores for each member of a class, in random order. You’d like a combined list of all the grades for each student, plus their average score. You have a text file (imaginatively named grades) that looks like this:
Noël 25 Ben 76 Clementine 49 Norm 66 Chris 92 Doug 42 Carol 25 Ben 12 Clementine 0 Norm 66 ...
You can use the following script to gather all their scores together, determine each student’s average, and print them all out in alphabetical order. This program assumes rather naïvely that you don’t have two Carols in your class. That is, if there is a second entry for Carol, the program will assume it’s just another score for the first Carol (not to be confused with the first Noël).
By the way, the line numbers are not part of the program, any other resemblances to BASIC notwithstanding.
1 #!/usr/bin/perl 2 use v5.14; 3 4 open(GRADES, "<:utf8", "grades") || die "Can't open grades: $!\n"; 5 binmode(STDOUT, ':utf8'); 6 7 my %grades; 8 while (my $line = <GRADES>) { 9 my ($student, $grade) = split(" ", $line); 10 $grades{$student} .= $grade . " "; 11 } 12 13 for my $student (sort keys %grades) { 14 my $scores = 0; 15 my $total = 0; 16 my @grades = split(" ", $grades{$student}); 17 for my $grade (@grades) { 18 $total += $grade; 19 $scores++; 20 } 21 my $average = $total / $scores; 22 print "$student: $grades{$student}\tAverage: $average\n"; ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access