punch_card_don has asked for the wisdom of the Perl Monks concerning the following question:

Milquetoast Monks,

Using cgi.pm:

$query = new CGI;
and of course referencing form parameters such as :
$language = $query->param('lang');
But how can I cycle through all the parameters, finding their names and values without knowing them in advance?

Thanks.




Forget that fear of gravity,
Get a little savagery in your life.

Replies are listed 'Best First'.
Re: How to cycle through CGI query params?
by ikegami (Patriarch) on Oct 25, 2006 at 00:40 UTC
    One of the first lines of the docs is "FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT". Once you know the name of the parameters, you can use them for "FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER".
    use CGI qw( escapeHTML ); my $cgi = CGI->new(); foreach my $param ($cgi->param()) { foreach my $value ($cgi->param($param)) { printf("<div>%s = %s</div>\n", escapeHTML($param), escapeHTML($value), ); } }
Re: How to cycle through CGI query params?
by punch_card_don (Curate) on Oct 24, 2006 at 23:46 UTC
    Found a tangential reference to it here

    http://www.perlmonks.org/?node_id=289954

    which lead to this:

    %hash = $query->Vars(); foreach $key (keys %hash) { print "<br> $key -> $hash{$key}\n"; }



    Forget that fear of gravity,
    Get a little savagery in your life.
Re: How to cycle through CGI query params?
by cLive ;-) (Prior) on Oct 25, 2006 at 01:52 UTC
    or...
    my %var = $query->Vars; for my $param (keys %var) { my $param_value = $var{$param}; }
    and it works just as well if you assign to a hashref rather than a hash.

      That doesn't display all the parameters, and gives the wrong value for some parameters. Fix:

      my %var = $query->Vars; foreach my $param (keys %var) { foreach my $value (split /\0/, $var{$param}) { ... } }
      and it works just as well if you assign to a hashref rather than a hash.

      There is a difference in the return value of Vars().
      If you request a hash this is obviously a copy of the param hash of the CGI object.
      If you request a a scalar you'll get a hashref, which is a variable tied to the CGI object, where the STORE/FETCH are implemented via the param() method of the CGI object.

      The latter has some implications if you ever decide to assign to that hashref. Since the FETCH is implemented with a join("\0", $cgi->param('x')); (for cgilib compatible multi-value parameter handling), assigning refs to the hashref will lead to confusing results (due to the forced stringification on reading):

      use CGI; use Data::Dumper; use strict; my $q = CGI->new; $q->param('form', 1 .. 5); my $h = $q->Vars(); $h->{'form'} = [ 4 .. 6 ]; print Dumper($h, $q);