Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: extracting the key value pairs from a string

by philipbailey (Chaplain)
on Jun 27, 2008 at 08:31 UTC ( #694337=note: print w/replies, xml ) Need Help??


in reply to extracting the key value pairs from a string

Or this?
my $s = ' ABC: 123 xyz: 100 def: YYY aaa: ZZZ'; my %hash; for (split /[^:]\s+/, $s) { my ($key, $val) = split /:\s*/; next unless $key; $hash{$key} = $val; }

Replies are listed 'Best First'.
Re^2: extracting the key value pairs from a string
by johngg (Abbot) on Jun 27, 2008 at 08:56 UTC
    split /[^:]\s+/, $s

    That's not going to do what you hoped as it will consume the last character of each value except the one at the end of the string. You can get around that by using a negative look-behind. I also use map to avoid the for loop and temporary variables.

    use strict; use warnings; use Data::Dumper; my $s = q{ ABC: 123 xyz: 100 def: YYY aaa: ZZZ}; my %extract = map { split m{\s*:\s*} } split m{(?<!:)\s+}, $s; print Data::Dumper->Dumpxs( [ \ %extract ], [ q{*extract} ] );

    This produces

    %extract = ( 'ABC' => '123', 'def' => 'YYY', 'aaa' => 'ZZZ', 'xyz' => '100' );

    I hope this is of interest.

    Cheers,

    JohnGG

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://694337]
help
Chatterbox?
[jedikaiti]: lolol
Tux looks up his status to find being an Abbot
[choroba]: pm-cb-g now shows the number of unread messages, commit on its way to github
[Tux]: choroba any plans for highlight patterns?
[choroba]: Tux feel free to submit a pull request :-)
[choroba]: I like the idea, but currently I only have time for small changes
[choroba]: but it should be a bit better in two weeks
[Tux]: time also lacks on this side to do more than tiny changes
[Tux]: running on a just pull'd pm-cb-g

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (13)
As of 2017-09-20 16:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    During the recent solar eclipse, I:









    Results (237 votes). Check out past polls.

    Notices?