It does provide the variable name (I'm assuming you mean the name of a parameter passed to your script). It's $_ in the for loop. davorg's answer should work well for you. It you'd like a little demonstration of getting the name/value pairs with CGI.pm, run the following CGI script:
#!C:\perl\bin\perl.exe -wT
use strict;
use CGI;
my $query = CGI->new;
my @names = $query->param; # Yup. That's all it takes to get all name
+s
# from name/value pairs.
print $query->header( "text/plain" ); # This is just to show that we c
+an
# specify our Content-type
foreach my $name ( @names ) {
# If we know that a particular name only has one value, we can use
# my $value = $query->param( $name );
# However, if we assign the param to a scalar and there are multip
+le
# values, we'll only get the first one.
my @values = $query->param( $name );
print $name . "=" . (join ", ", @values) . "\n";
}
Each $name is the "variable" and @values contains the associated values. The reason that I assigned to an array in this example is because the following query string is quite legal:
color=blue&color=red&color=hot%20pink
Note that the above code snippet works fine for both GET and POST methods. However, it does have one little flaw that you should be aware of: it doesn't escape potentially harmful HTML entities. That can leave your script open to annoying problems if you're just printing the values to a page (for example, if someone enters a meta refresh tag or a link to a pornographic image, you might have problems). To get around this, use URI::Escape with its associated uri_escape() function.
Cheers,
Ovid
Update: Oops! Not URI::Escape! I mean HTML::Entities. Sigh.
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats. |