Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: How to create a hash from string

by Tux (Monsignor)
on Aug 09, 2013 at 11:22 UTC ( #1048748=note: print w/ replies, xml ) Need Help??


in reply to How to create a hash from string

Both given answers are fine, but this smells like records embedded in CSV, where both answers will soon fail. What if x is allowed to be This, my friend, is why : is allowed in "text" to fail?

update: additional remarks:

In case that cannot happen, stick to the earlier answer. They are fast and simple. In case it /can/ happen, you need a double CSV parser. The first to split on , the second on ::

my $outer = Text::CSV_XS->new ({ binary => 1, auto_diag => 1 }); my $inner = Text::CSV_XS->new ({ binary => 1, auto_diag => 1, sep_char + => ":" }); my %hash; while (my $row = $outer->getline ($fh)) { foreach (@$row) { $inner->parse ($_); my @f = $inner->fields; if (@f >= 2) { # assuming key:value:1 will result in $hash{key +} = "value:1" my $key = shift @f; $hash{$key} = join ":" => @f; } else { warn "Probably not a key-value pair '$_'"; } } }

which is likely to get more and more complicated as you proceed.


Enjoy, Have FUN! H.Merijn


Comment on Re: How to create a hash from string
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (11)
As of 2014-07-23 18:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (149 votes), past polls