Sunday, July 24, 2011

getting variables from GET method in perl (cgi)

Suppose we have a page with the following form:

<form action="index.pl" method="get">
<input type="text" name="search_for" size="30" />
<input type="submit" value="search" />
</form>

So, there's a text input field named "search_for", and a submit button.
The following code gets the variables set in QUERY_STRING (whatever is after pagename.pl?...), into the $arg associative array. So we can get the value of "search_for" by $arg{"search_for"}.

for (split /\&/, $ENV{QUERY_STRING}) {
($key,$val) = split /\=/;
$val =~ s/\+/ /g;
$val =~ s/%([0-9a-fA-F]{2})/chr(hex($1))/ge;
$arg{$key} = $val;
}
print "data searched for is =
$arg{search_for}
";

No comments:

Post a Comment

Sociable