Forum Moderators: coopster & phranque

Message Too Old, No Replies

Something like PHP's parse str() for Perl

         

csdude55

5:22 am on Mar 11, 2019 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



When I submit a script via Ajax, the only way I could make it work was to send the query string like this:

https://example.com/?query_string=varA=1&varB=2&varC=3

And I url encode the string in Javascript, like so:

'query_string=' + encodeURIComponent(varA=1&varB=2&varC=3)


In Javascript, encodeURIComponent('whatever') encodes everything except for A-Z a-z 0-9 - _ . ! ~ * ' ( ), so it ends up sending:

https://example.com/?query_string=varA%3D1%26varB%3D2%26varC%3D3

In PHP, I parse it like this:

parse_str($_GET['query_string'], $_GET);


Which seems to work out great for my purposes.

But now I need a Perl script to receive the form, and I need to send the variables to %contents. In the end, the script would see:

$contents{'query_string'} => "varA=1&varB=2&varC=3"
$contents{'varA'} => "1"
$contents{'varB'} => "2"
$contents{'varC'} => "3"


I'm already parsing it so that $contents{'query_string'} is set correctly, but now I'm working on parsing $contents{'query_string'}.

I have this, which works:

%contents = split(/[&=]/, $contents{'query_string'});


I was concerned that encoding it this way would break if varA=1&2 or something, but so far it seems to be working just fine.

So is that one-liner an acceptable way to parse $contents{'query_string'} the way I need it? Or am I going to have problems down the road?

phranque

7:17 am on Mar 11, 2019 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



a valueless parameter in a query string is definitely a legitimate usage, so if you want your script to work for the most general case, you should code for that.
i would suggest splitting the query string on the ampersand(s) and then handle each parameter (or parameter=value pair) in a for loop.

phranque

7:50 am on Mar 11, 2019 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



you might also consider using one of the lighter weight CGI modules on CPAN [metacpan.org]