Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Parsing Challenge

by gumpu (Friar)
on May 24, 2001 at 22:54 UTC ( [id://83069]=note: print w/replies, xml ) Need Help??


in reply to Parsing Challenge

How about:

my $data = "aap=10 20 30 noot=50 60 mies=20 teun=3"; my %foo; while ($data =~ m/(\S+)=(\S+($|([^=]+\s+)+))/g) { $foo{$1}=$2; }

If needed $2 can be further split into indivual values.

Have Fun

Replies are listed 'Best First'.
Re: Re: Parsing Challenge
by Albannach (Monsignor) on May 24, 2001 at 23:14 UTC
    Though we have arrived at very similar solutions, I think yours fails to pick up multiple values for the last key:
    use strict; use warnings; use Data::Dumper; my $data="key1=value1 key2=value2 value3 key3=value4 value5 value6 key +4=value7 key5=value8 key6=value9 value10"; # Albannach version my %hash; while ($data =~ /(\w+=)((\w+( |$)+)+)/g) { $hash{$1} = $2; } print Dumper \%hash; # gumpu version: my %foo; while ($data =~ m/(\S+)=(\S+($|([^=]+\s+)+))/g) { $foo{$1}=$2; } print Dumper \%foo;
    Produces:
    $VAR1 = { 'key4=' => 'value7 ', 'key5=' => 'value8 ', 'key1=' => 'value1 ', 'key6=' => 'value9 value10', 'key2=' => 'value2 value3 ', 'key3=' => 'value4 value5 value6 ' }; $VAR1 = { 'key1' => 'value1 ', 'key2' => 'value2 value3 ', 'key3' => 'value4 value5 value6 ', 'key4' => 'value7 ', 'key5' => 'value8 ', 'key6' => 'value9 ' };

    Update: The = in the key? You are right of course - silly me! Thanks gumpu!

    --
    I'd like to be able to assign to an luser

      It does not pick up the last value for the last key, should have tested it better. I also think that your version is more readable. Though I would leave out the = from the key.

      $hash{$1} = $2 while ($data =~ /(\w+)=((\w+( |$)+)+)/g);

      Have Fun

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-03-29 02:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found