in reply to Parsing a text file
I would first encourage you to Use strict and warnings.
A hash would work well for this application. If you're using strict, you can declare it like so:
my %total_for;
Then you can access the elements by operator name.
my $operator = 'Nicole'; $total_for{$operator} = 123; # total for Nicole is 123 $total_for{$operator} += 45; # increase Nicole's total by 45.
You can loop over the names using keys like so:
foreach my $operator ( sort keys %total_for ) { print "Total for $operator: $total_for{$operator}\n"; }
I also used sort here because the keys come out in no particular order.
A few other notes:
open(LOG, $file) or die "Can't read '$file': $!";
while (<LOG>) { @tmpwords = split; # etc. }
foreach my $blah ( @array ) { # use $blah instead of $_ for things }
Update: Since others have posted full working solutions now, I might as well also (I was trying to treat this as a student).
use strict; use warnings; my $file = 'msgcount.txt'; open my $fh, '<', $file or die "Can't read '$file': $!"; my %total_for; while ( <$fh> ) { my $line = $_; chomp; s{ \A \d\d / \d\d / \d{4} \s+ }{}xms or die "line does not match: $line"; my ( $name, $numb ) = m{ \A ( .+ ) \s+ ( \d+ ) \s* \z }xms; if ( ! $name ) { die "line does not match: $line"; } $total_for{ $name } += $numb; } close $fh or die "Failed to close: $!"; foreach my $operator ( sort keys %total_for ) { print "Total for '$operator': $total_for{$operator}\n"; }
This accounts for the suggestion from mr_mischief (in case names are not all non-spaces). It will die if it hits a line outside the format it expects. I haven't run it.
|
|---|