in reply to Re: Split pattern doesn't match last line of file
in thread Split pattern doesn't match last line of file

++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.

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: $!"; }