in reply to first perl example from perl book

DAT should be DATA.

As for your second question, the quoted line appends a space character before appending to the hash value. Your rewrite leaves out the space character. This may be significant.

Replies are listed 'Best First'.
Re^2: first perl example from perl book
by convenientstore (Pilgrim) on Jan 15, 2008 at 07:12 UTC
    thank you!!
    #!/usr/bin/perl -w use strict; my %grades; while (<DATA>) { chomp; my($student,$grade) = split (" ",$_); $grades{$student} .= $grade . " "; #$grades{$student} = $grade; print "\$grades{$student} is $grades{$student}\n"; } for (sort keys %grades) { my $scores = 0; my $total = 0; my @grades = split(" ", $grades{$_}); for (@grades) { $total += $_; $scores++; } my $average = $total / $scores; print "$_: $grades{$_}\tAverage: $average\n"; } __END__ lee 90 lee 100 kim 90 kim 90 ./././perl.score $grades{lee} is 90 $grades{lee} is 90 100 $grades{kim} is 90 $grades{kim} is 90 90 kim: 90 90 Average: 90 lee: 90 100 Average: 95 so $grades{$student} .= $grade . " "; is more like $grades
    I also tried this for just education.(which btw is not the same solution and answer).
    #!/usr/bin/perl -w use strict; use diagnostics; my %grades; my %student_n; while (<DATA>) { chomp; my($student,$grade) = split (" ",$_); $grades{$student} += $grade; $student_n{$student}++; } for (sort keys %grades) { my $avg = $grades{$_} / $student_n{$_}; print "$_ average of $student_n{$_} exams are $avg\n"; } __END__ lee 90 lee 100 kim 90 kim 90 ~ ./././././perl.score_copy kim average of 2 exams are 90 lee average of 2 exams are 95
      so
      $grades{$student} .= $grade . " "; is more like

      $grades


      No. It is this:
      $grades{$student} = "$grades{$student}$grade ";

      The value of $grade, followed by a space (" "), is appended to any existing value of $grades{$student}. The . operator does texual concatination, whereas += is numeric, and will add the right-hand-side to the left. For example:
      $x = 3; $y = 4; $x .= $y; # gives 34 $x += $y; # gives 7

      No. It's more like

      $grades{$student} = $grades{$student} . $grade . " ";