yabba has asked for the wisdom of the Perl Monks concerning the following question:

OK, I'm really stuck now. This is what I have so far:
use strict; my $number=0; float: my $line; float: my $score; float: my $std; float: my $avg; float: my $name; float: my $sum; open(IN, "pa5c.dat") || die ("Can't open file $!\n"); while($line = <IN>){ chomp($line); ++$number; $sum = $sum + $score; ($name, $score) = split(/:/, $line); print "$name $score\n"; } $avg = $sum / $number; printf "%3.2f\n", $avg; __END__#pa5.pl
Now, when I run it, the average comes out as 62.33 instead of 75.00 The file contains 6 scores: 70 74 80 82 68 76. But for some reason, its not reading the last score of 76. HELP ME PLEASE!!

Edit Masem 2001-12-19 - Edited title from "HELP" to fix searching problems

Replies are listed 'Best First'.
Re: HELP
by Trimbach (Curate) on Apr 08, 2001 at 03:04 UTC
    The last number isn't being added because you aren't reading the last number till AFTER you add the $score to $sum.

    In other words, when you begin reading the file you're adding $score to $sum before $score even has anything in it. The second line that's read first adds the FIRST score, then sets $score to the second number. And so on. The last number is never added because the loop exits before $sum has a chance to get $score added to it.

    Move $sum = $sum + $score to after your split and that should fix it.

    In other news, that "float:" stuff you're doing when declaring your variables doesn't do what you think. "float:" is a block name in Perl... it has nothing to do with type declaration. Perl is not a strongly typed language. Variables will be treated as they ought to be treated... numbers as numbers and strings as strings. Most of the time that's The Right Thing, so don't worry about the fact that you can't declare your vars as floats. Because, in most situations, you can't.

    Gary Blackburn
    Trained Killer

      THANKS AGAIN!!
(jeffa) Re: HELP
by jeffa (Bishop) on Apr 08, 2001 at 03:04 UTC
    Looks like you need to reverse these two lines:
    # the first time through the loop, $score has no value! $sum = $sum + $score; ($name, $score) = split(/:/, $line);
    like this:
    ($name, $score) = split(/:/, $line); $sum = $sum + $score;

    Jeff

    R-R-R--R-R-R--R-R-R--R-R-R--R-R-R--
    L-L--L-L--L-L--L-L--L-L--L-L--L-L--
    
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: HELP
by mikfire (Deacon) on Apr 08, 2001 at 03:01 UTC
    Please use more descriptive titles and please swap the lines where you add the *previous* score and then split() to get the current score.

    mikfire