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:
- Use 3 parameter open: open my $fIn, '<', $ARGV[0]
- die not print for failure - there's no point continuing.
- Show the file and error in the failure message - it's easier to figure out what went wrong.
- 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).
- Use the regular expression match to extract the interesting data into named variables.
- 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).
- 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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.