Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k & phranque

Message Too Old, No Replies

extracting key-value pair from an url with perl


Warboss Alex

12:02 am on Mar 31, 2006 (gmt 0)

10+ Year Member

hey all,

I've got an url of the form


and I'm just trying to extract the 'data' values, not the rest. I tried extracting from?data= to the first & it finds like this:

$bits =~ s/(q\=)(.+)(&)/$2/

but it doesn't work .. is the ampersand a special character? what am I missing? :(

thanks in advance!


1:41 am on Mar 31, 2006 (gmt 0)

5+ Year Member

why aren't you using CGI.pm to do this?


5:08 am on Mar 31, 2006 (gmt 0)

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member

. . . or any other read/parse. But he may be examining a string. The mechanics could go like

$url = 'www.server.com?data=a+b+c&other_data=f';
($dom,$query_string) = split (/\?/,$url);

foreach $pair (split(/&/, $query_string)) {
($_n, $_v) = split(/=/, $pair);
## A full unpack is not required, all you have to deal with are spaces probably
$_v =~ s/[\+\%20]/ /g;
$qs{$_n} = $_v;

## you now have everything stored in a hash, or associative array, named %qs

print "content-type: text/html\n\n";
print "From URL $dom <br>\n";
foreach $k (keys %qs) {
print "key: $k value: $qs{$k} <br>\n";

## This should print

#www.server.com <br>
#key: other_data value: f <br>
#key: data value: a b c <br>

## so if you just wanted 'data'
print "$qs{'data'} <br>\n";


6:39 am on Mar 31, 2006 (gmt 0)

5+ Year Member

you can still use CGI.pm if it's a string or reading input from a file, etc.

use CGI;
my $uri_string = 'www.server.com?data=a+b+c&other_data=f';
my $data = (split(/\?/,$uri_string))[1];
my $q = new CGI($data);
print $q->header;
my %data = $q->Vars;
print map {"$_ = $data{$_}$/"} (keys %data);

Warboss Alex

1:26 pm on Mar 31, 2006 (gmt 0)

10+ Year Member

thanks guys

I was over complicating everything. :/

everything is fine now :)


Featured Threads

Hot Threads This Week

Hot Threads This Month