++bobf; I often used that line, but recently changed to using this form of it:
next if not /\S/; # Skip blank lines
I found that it was too easy to leave out (via typo) the
^,
+, or
$ in
m/^\s+$/, and too hard to verify by eye.
With my brain under the influence of Perl Best Practices, I see some possible bugs, and opportunities for improvements.
- %saldi is not getting cleared between files! Is this what you want?
- Magic <> is nice, but when you need eof() processing over multiple files, consider changing to do your own opens/closes, etc.
- Sort your hash keys, or your output order may vary between runs.
- Your totals will not line up when printed; consider printf() to format the output.
- The code will be clearer if you name your fields instead of treating them as numbers, especially since the numbers change! (fields 3,4 become 0,1)
- You are not chomping your input, so your last field contains newlines. It has not caused problems because the last field is only handled numerically.
Working, tested example code:
use strict;
use warnings;
foreach my $filename (@ARGV) {
open my $fh, '<', $filename
or warn "Can't open $filename: $!"
and next;
my %saldi;
while ( <$fh> ) {
chomp;
next if not /\S/; # Skip blank lines
my @fields = split /,/;
if ( @fields != 5 ) {
warn "Bad number of fields in file '$filename' line $.";
next;
}
my ( $department, $currency, $year, $type, $amount ) = @fields
+;
$saldi{ $type } += $amount;
}
my ($basename) = ( $filename =~ m/^(\S+)\.txt/ )
or warn;
print "$basename\n";
foreach my $type ( sort keys %saldi ) {
my $total_amount = $saldi{$type};
printf "\t%-7s\t%7.2f\n", $type, $total_amount;
}
close $fh
or warn "Can't close $filename: $!";
}
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.