in reply to Re: A Beginner Needs Homework help
in thread A Beginner Needs Homework help

And here it is cleaned up a little:

#!/usr/bin/perl use strict; use warnings; my %myhash; open my $fIn, '<', $ARGV[0] or die "could not open '$ARGV[0]': $!\n"; while (defined (my $line = <$fIn>)) { my ($word, $value) = $line =~ m/(\w+):(-?\d+)/; $myhash{$word} += $value; } while (my ($key, $value) = each %myhash) { print "$key: $value\n"; }

Prints:

green: 311 blue: 45 red: 27 yellow: 114

Not the following changes:

  1. Use 3 parameter open: open my $fIn, '<', $ARGV[0]
  2. die not print for failure - there's no point continuing.
  3. Show the file and error in the failure message - it's easier to figure out what went wrong.
  4. Don't "slurp" the file contents into an array - use a while loop and handle the data a line at a time. The code is clearer, shorter and has less memory overhead (although the last is not usually an issue).
  5. Use the regular expression match to extract the interesting data into named variables.
  6. Use += to update the hash values. This avoids the "Use of uninitialized value in addition" the first time each new colour is added (and it's a whole lot shorter).
  7. Take advantage of Perl's string interpolation to clean up the print: print "$key: $value\n";

Note that "short code" is not an end in itself, but the fewer (sensible) lines of code you have generally the easier it is to understand and maintain the code.

Perl is the programming world's equivalent of English