Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^4: How can I group lines in a file?

by bichonfrise74 (Vicar)
on May 17, 2009 at 06:05 UTC ( [id://764482]=note: print w/replies, xml ) Need Help??


in reply to Re^3: How can I group lines in a file?
in thread How can I group lines in a file?

oops, my bad. When I was writing my own version, I used "split" to get the values which is basically the regex thing that BrowserUk did. Also, my version is similar to what you just wrote... Read the file, get the values, push it in a hash of array.

But BrowserUk's version was done in a single line which I'm still perplexed. Why does it work? (regex thing "and" pushing it in a hash of array).

How does "and" work? How can it get the regex values and push it to HoA? Thanks.

Replies are listed 'Best First'.
Re^5: How can I group lines in a file?
by BrowserUk (Patriarch) on May 17, 2009 at 07:00 UTC
    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] }

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://764482]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (4)
As of 2026-03-09 09:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.