On Fri, Jul 06, 2001 at 01:06:00PM -0400, David Gilden wrote:
> I am trying with out much success to get the following to happen:
> 
> Using this statement:
> 
> $average =  sprintf ("%2.1f", ($total / $scores));
> 
> I want my numbers to line up like so: [note the left padding with the ' ']
> 
> fred         72         18.0  # with or with out the trailing '0'
> joan         15          3    # would like to know how to accomplish both!
> john         21          3.5
> ----
> 
> this what you might get after running the script as is:
> ----------------------------------------------
> fred         72         18.0
> joan         15         3.0
> john         21         3.5
> 
> 
> --- script --
> 

Please, for the sake of people having to read your code (like me), use
whitespace.  Oh, and you forgot use strict, and possibly -w.

Listed below is how I would accomplish this task (well, not entirely; I
avoid formats like the plague; I'd use printf instead).

I changed the structure of %grades, it's now a hash of hashes.  This is so
the total can be calculated in the first loop, rather than a third loop
within your grades foreach loop.  The grades list has also been turned into
an actual array, where before it was just a string that you split and
rejoined, effectively reparsing it each time.  It's not as important now
that it be an array, because I've obviated the need to reparse it, but if
you're dealing with list data you should use an array.

The requested change, stripping the decimal off if it's 0, is a simple
substitution down near where the average is calculated.


    #!/usr/bin/perl -w

    use strict;
    use vars qw($student %grades $average);


    open (GRADES, "grades.txt") || die "Can't open grades $!\n";


    my $scores;
    while (my $line = <GRADES>) {
        my($student, $grade) = split(" ", $line);

        push(@{ $grades{$student}{'grades'} }, $grade);
        $grades{$student}{'total'} += $grade;
        $scores++;
    }


    foreach $student (sort keys %grades) {
        $average =  sprintf("%2.1f", $grades{$student}{'total'} / $scores);
        $average =~ s/\.0$/  /;
        write;
    }



    format STDOUT_TOP =
    Page @<<
    $% # page number variable 
    Student     Score     Average
    -----------------------------
    .


    format STDOUT =
    @<<<<<<<<<<  @<<        @>>>>
    $student, join(" ", @{$grades{$student}{'grades'}}), $average
    .


Michael
--
Administrator                      www.shoebox.net
Programmer, System Administrator   www.gallanttech.com
--

Reply via email to