Mike Tran wrote: > > The code below is what I got so far, but I'm still getting the "|0.0" > for the first row returned. I don't know which part of the code is > generating this, could someone help explain this to me? Thanks for all > your help. > > new_ratings.txt: > > base_no|AvgRating > |0.0 > 10000|4.7 > 10007|4.5 > 10008|2.5 > > > > #!/usr/bin/perl > ####################################################################### > # This script reads through reviewsRating.txt and calculates an average > # > # rating for each base_no > # > ####################################################################### > > use strict; > use warnings; > > my %numsum; > my %numcnt; > my $output= 'new_ratings.txt'; > my $file ='reviewsRating.txt'; > > #Open output file to print header row > open(OUT,">$output") or die "Could not open $output: $!"; > print OUT "base_no|AvgRating\n"; > close(OUT); > > open my $fh, '<', $file or die $!; > open OUT, '>>', $output or die "Could not open '$output' $!"; > > while(<$fh>){ > next if $. == 1; # exclude header > chomp; > my ($num, $rate) = split/\|/; > $numsum{$num} += $rate; > ++$numcnt{$num}; > } > for (sort keys %numsum){ > my $numavg = sprintf "%.1f",$numsum{$_} / $numcnt{$_}; > print OUT "$_\|$numavg\n"; > } > close($fh); > close(OUT);
Hi Mike Your code looks like it should work. Your extra output line is probably because there is a blank line in the input file. I suggest you check that the base number in each line is valid before you accumulate it, like this: while (<$fh>){ chomp; my ($num, $rate) = split/\|/; next unless $num =~ /^\d+$/; $numsum{$num} += $rate; ++$numcnt{$num}; } Also, I assume you realise there's no need to close and reopen the output file? And your indenting could use some work. HTH, Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/