Home > Archive > PERL Beginners > March 2007 > The first example from "Camel" 3rd Ed seems odd.
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
The first example from "Camel" 3rd Ed seems odd.
|
|
| aircawn@gmail.com 2007-03-22, 9:58 pm |
| Hi.
I'm looking at the first example on page 18 of Camel 3rd Ed. It's
description is it tallys up all the student's grades and prints out
the average. But the way it is structured, as it iterates through each
$student in %grades, it resets the counters $scores and $total that
are used to calculate $average later.
Am I reading it incorrectly or am I giving it too much attention? :)
| |
| Paul Lalli 2007-03-22, 9:58 pm |
| On Mar 22, 5:54 am, airc...@gmail.com wrote:
> I'm looking at the first example on page 18 of Camel 3rd Ed. It's
> description is it tallys up all the student's grades and prints out
> the average. But the way it is structured, as it iterates through each
> $student in %grades, it resets the counters $scores and $total that
> are used to calculate $average later.
>
> Am I reading it incorrectly or am I giving it too much attention? :)
You're reading the description incorrectly. It's not printing the
average of ALL students' grades. It's printing the average of EACH
student's grades. That is, it will print one average for each student
in the class. Therefore, it resets $scores and $total for each
subsequent student.
This is a purely learning example, by the way, and should not be
copied for any real-life example. If you were really doing this
example, you would use a hash of array references, rather than
concatenation in the first loop and splitting in the second loop.
Something like this:
#!/usr/bin/perl
use strict;
use warnings;
my %grades;
open my $GRADES, '<', 'grades' or die "Can't open grades: $!\n";
while (my $line = <$GRADES> ) {
chomp $line;
my ($student, $grade) = split(' ', $line);
push @{$grades{$student}}, $grade;
}
foreach my $student (sort keys %grades) {
my $total = 0;
my $scores = @{$grades{$student}};
foreach my $grade (@{$grades{$student}}) {
$total += $grade;
}
my $average = $total / $scores;
print "$student: @{$grades{$student}\tAverage: $average\n";
}
Hope this helps,
Paul Lalli
| |
|
|
|
|
|