in reply to Re^4: How can I group lines in a file?
in thread How can I group lines in a file?
Why does this line work? /(\S+)\s+(\S+)/ and push @{ $HoA{ $1 } }, $2 while <$fh>;
The regex matches against $_ (which is set to each line in turn by the while), and sets $1 to the first whitespace delimited 'word', and $2 to the second.
The and checks that the line matches, and if it does pushes the second 'word' onto an array within the hash keyed by the first word.
You can also tighten the regex a tad and add some error checking:
#! perl -slw use strict; use Data::Dump qw[ pp ]; my %HoA; open my $fh, '<', 'junk.dat' or die $!; /(\S+)\s+(\d+)/ and push @{ $HoA{ $1 } }, $2 or warn "Bad data '$_' at line $.\n" while <$fh>; close $fh; pp \%HoA; __END__ c:\test>junk Bad data 'the quick brown fox ' at line 5 { ernest => [38, 27], jim => [14, 34], john => [23, 44], matilda => [4 +3, 22] }
|
|---|