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:#!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"; }
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.color=blue&color=red&color=hot%20pink
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.
In reply to (Ovid - here's another example) Re(5): Pushing w/ an associative array?
by Ovid
in thread Pushing w/ an associative array?
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |