Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Parsing Challenge

by blue_cowdawg (Monsignor)
on May 24, 2001 at 22:28 UTC ( [id://83048]=note: print w/replies, xml ) Need Help??


in reply to Parsing Challenge

How about this:

#!/usr/bin/perl -w ############################################################### use strict; use Data::Dumper; my $data=qq(key1=value1 key2=value2 key3=value3 key4=value4); my $v={}; foreach my $pair (split(' ',$data)) { my($key,$value)=split('=',$pair); $v->{$key}=$value; } print Dumper($v);

Yields:

$VAR1 = { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4' };

Alternatively you can do the following with the same results

#!/usr/bin/perl -w ############################################################### use strict; use Data::Dumper; my $data=qq(key1=value1 key2=value2 key3=value3 key4=value4); my $v={}; map { my($k,$vl) = split('=',$_); $v->{$k}=$vl; } split(' ',$data); print Dumper($v);

HTH


Peter L. BergholdSchooner Technology Consulting, Inc.
Peter@Berghold.Netwww.berghold.net

Replies are listed 'Best First'.
Re: Re: Parsing Challenge
by no_slogan (Deacon) on May 24, 2001 at 22:37 UTC
    Some of the keys have multiple values, though. You could remember the last key...
    foreach (split " ", $data) { if (/^([^=]*)=(.*)/) { $hash{$last=$1}=$2 } elsif (defined $lastkey) { $hash{$last} .= " $_" } }
    Since "key=" is easy to recognize, another way would be to use split:
    %hash = ("JUNK", split /([^=\s]*)=/, $data)
    if you don't mind the JUNK, that is.

      What if the literal "key" is not always present? What if the pairs become:

      my $data="fruit=apple meat=steak ....";


      Peter L. BergholdSchooner Technology Consulting, Inc.
      Peter@Berghold.Netwww.berghold.net

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2024-04-26 03:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found