To get a reference to an anonymous hash containing all params and values, do this:
my $q = CGI->new(); my $params = $q->Vars; print $params->{'foo'}; # one
If you prefer getting a named hash instead of a hashref, do this:
my $q = CGI->new(); my %params = $q->Vars; print $params{'foo'}; # one
Update (additional info): This is documented in the POD for CGI:
Many people want to fetch the entire parameter list as a hash in which the keys are the names of the CGI parameters, and the values are the parameters' values. The Vars() method does this. Called in a scalar context, it returns the parameter list as a tied hash reference. Changing a key changes the value of the parameter in the underlying CGI parameter list. Called in a list context, it returns the parameter list as an ordinary hash. This allows you to read the contents of the parameter list, but not to change it.When using this, the thing you must watch out for are multivalued CGI parameters. Because a hash cannot distinguish between scalar and list context, multivalued parameters will be returned as a packed string, separated by the "\0" (null) character. You must split this packed string in order to get at the individual values. This is the convention introduced long ago by Steve Brenner in his cgi-lib.pl module for Perl version 4.
Update2 (afterthought): Just to be thorough, I wanted to show the technique that will give you a named hash with multi-values placed into anonymous arrays:
my $q = CGI->new(); my %hash = $q->Vars(); foreach my $key ( keys %hash ) { my $values = $hash{$key}; $hash{$key} = [ split /\0/, $values ]; }
Now you'll have a HoA (hash of arrays). This takes care of the potential for multi-value keys by placing all values into anonymous arrays referred to by the individual hash elements. It's now a 2d structure. Plan accordingly ;)
HTH
Dave
In reply to Re: Populating a Perl associative array with form values
by davido
in thread Populating a Perl associative array with form values
by nenbrian
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |