Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Using Split to load a hash

by rodion (Chaplain)
on Aug 19, 2006 at 15:06 UTC ( [id://568362]=note: print w/replies, xml ) Need Help??


in reply to Using Split to load a hash

I'm not sure what you have in mind. This may be the kind of example you want, of a split into a hash. If so, you can then change the "for" loop to a "while(<FILEHANDLE>)".
my $txt=<<'TEXT_END'; nameone, addr1 info (without commas in it) nametwo, address two, city (with a comma) namethree, address three fields TEXT_END my %info; my ($name,$addr); for (split "\n",$txt) { ($name,$addr) = split ',',$_,2; $info{$name} = $addr; } my ($key,$val); while (($key,$val)= each(%info)) { print "$key->$val\n"; }
Update: Added ",$_,2" to the split, to handle addresses with a comma, and modified test cases acordingly

Replies are listed 'Best First'.
Re^2: Using Split to load a hash
by izut (Chaplain) on Aug 19, 2006 at 17:59 UTC

    Another possible method (borrowed from "Perl for System Administrators"):

    my %info = split /,|\n/, $txt;

    This will possible fail if the second field has comma. Maybe we can work it out to prevent that :-)

    Igor 'izut' Sutton
    your code, your rules.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2024-03-28 08:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found