http://qs321.pair.com?node_id=763206

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?

Thanks

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.

    -d.