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

So I'm just learning perl so I hope you don't mind me posting already, or with simple questions.

I'm trying to write a simple program that creates a list of Students' grades and average grades on assignments from a text file. I can get the first part to work and get the proper calculations for the second. However when I try to sort the arrau then my output doubles and have of it comes with an error

Use of uninitialized value in print at ./hw3.pl line 30, <STDIN> line 9.

here is the code:
#!/usr/bin/perl -w %totals = (), %hwsum = (), %hwtimes = (); while ($line = <STDIN>) { chomp $line; ($student, $assign, $grade) = split /:/, $line; $totals{$student} += $grade; $hwsum{$assign} += $grade; $hwtimes{$assign} += 1; $average{$assign} = $hwsum{$assign} / $hwtimes{$assign}; } @all = keys %totals; @all = sort {$totals{$b} <=> $totals{$a}} @all; @hwall = keys %average; @hwall = sort (%average); print "*** STUDENT TOTALS ***\n"; foreach $st (@all) { print $st, ": ", $totals{$st}, "\n"; } print "*** HOMEWORK AVG ***\n"; foreach $phw (@hwall) { print $phw, ": ", $average{$phw}, "\n"; }
and here is the output
*** STUDENT TOTALS *** cindy: 24 david: 19 alice: 15 bob: 11 *** HOMEWORK AVG *** Use of uninitialized value in print at ./hw3.pl line 30, <STDIN> line +9. 7: Use of uninitialized value in print at ./hw3.pl line 30, <STDIN> line +9. 8: Use of uninitialized value in print at ./hw3.pl line 30, <STDIN> line +9. 8: hw1: 8 hw2: 8 hw3: 7

Thanks for any help

--Jeeves

20050413 Janitored by Corion: Added code tags

Replies are listed 'Best First'.
Re: New to Perl, getting funny results when sorting an Array
by davido (Cardinal) on Apr 13, 2005 at 03:00 UTC

    Here's one mistake:

    @hwall = keys %average; @hwall = sort (%average);

    What you probably meant was:

    @hwall = keys %average; @hwall = sort { $average{$a} <=> $average{$b} } @hwall;

    ...at least that is if I understand your intent. I may have misunderstood it, making my solution in error, but the second line I pointed out definately is a bug. ;)


    Dave

      Or if you prefer:

      @hwall = sort { $average{$a} <=> $average{$b} } keys %average;

      I noticed you enabled warnings with the -w switch, but don't forget to use strict as well. If you're having trouble making sense of the error messages, try use diagnostics.

Re: New to Perl, getting funny results when sorting an Array
by rev_1318 (Chaplain) on Apr 13, 2005 at 07:38 UTC
    BTW Use of uninitialized value in print at ./hw3.pl line 30, <STDIN> line 9 is a warning, not an error. It simply warns you that a variable has not been initialized (=undef). That can be intentional, but often indicates a programming error like, when not using strict, a typo.
    As others pointed out, make a habit of adding use strict in your programs.

    Paul