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


in reply to Best way to parse CGI params

A note regarding CGI::Vars(): I never use it. It was created to ease the transition from the Perl4 cgi-lib.pl and the Perl5 CGI.pm. As a result, it uses the NUL byte (ASCII zero) to delimit multiple values. Since the NUL byte hack is so dangerous, I prefer not not to deliberately introduce them.

One quick and easy way of getting all params is the following:

my %param = map { $_ => [$cgi->param($_)] } $cgi->param;

Some might prefer the following:

#!/usr/bin/perl -wT use strict; use CGI qw/:standard/; my %params = map { $_ => get_data( $_ ) } param; sub get_data { my $name = shift; my @values = param( $name ); return @values > 1 ? \@values : $values[0]; }

With the last snippet, if you only have one param value, the hash value is a scalar value. If you have multiple param values, the hash value is a reference to an anonymous array.

I used to think the last method was better, but as tilly alluded to above, and as I have seen before, most code that uses the ref function has problems. Most of the time, such code can be rethought to more naturally model the problem without having to insert a lot of extra logic to see what type of reference you are getting at any given time. Of course, that comes with the caveat that the only hard and fast rule is that there are no hard and fast rules.

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Replies are listed 'Best First'.
Re: (Ovid) Re: Best way to parse CGI params
by KILNA (Acolyte) on Feb 15, 2002 at 23:07 UTC
    Actually you have just inspired my new one-line drop-in replacement for $cgi->Vars()...
    $params = $cgi->Vars();
    ... becomes ...
    $params = { map { $_ => ($cgi->param($_))[0] } $cgi->param };
    ... or if you want a straight hash instead of the hashref that Vars() gives you, you can ...
    %params = map { $_ => ($cgi->param($_))[0] } $cgi->param;
    This way seems DWIMmer since it returns what I expect most people *think* $cgi->Vars() does, which is a hash with a single scalar as the value, which ignores multiple instances of cgi params. I can't think of any time where I've actually needed multiple instances of the same name CGI parameter back (Then again, I avoid multi-select boxes ;). If I do need multiple values, you can still get at them via $cgi->param('foo'), or Ovid's method. Since mine doesn't require dereferencing the arrayref, it may be a little more convenient for newbies.

    -- KILNA - pop music for cyborgs - http://www.kilna.com