Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Spliting on Key/value pairs

by Anonymous Monk
on May 11, 2009 at 10:14 UTC ( #763206=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Enjoying playing with SQL::Abstract to generate SQL from values in a database table. This is working really well so far in my experiments. I've a little routine which determines how to call use SQL::Abstract's ‘where’ clauses correctly depending on what I need.

My problem is that one field I have to deal with contains key value pairs which I need to split up and pass to this routine. Their form is "&keyname=value&keyname2=value2". How can I sensibly split these up?


Replies are listed 'Best First'.
Re: Spliting on Key/value pairs
by przemo (Scribe) on May 11, 2009 at 10:34 UTC

    Looks like part of URL. You can parse it using split or regex, or use CGI::Simple:

    use warnings; use strict; use CGI::Simple; my $query = '&keyname=value&keyname2=value2&keyname2=value3'; my $c = CGI::Simple->new($query); for my $p ($c->param) { printf "%s: %s\n", $p, join(',', $c->param($p)); } __END__ keyname: value keyname2: value2,value3

Re: Spliting on Key/value pairs
by allolex (Curate) on May 11, 2009 at 10:26 UTC

    You could do something like this:

    my $string = '&keyname=value&keyname2=value2'; # eliminate the first ampersand for cleaner output $string =~ s/^&//; foreach ( split /&/, $string ) { printf "Key: %s, Value: %s\n", split /=/; }

    I'd also look on CPAN for something that parses URL queries.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://763206]
Approved by GrandFather
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2020-11-30 11:00 GMT
Find Nodes?
    Voting Booth?

    No recent polls found