in reply to making a hash from cgi parameters

Or:

use CGI qw(:standard); my %data = map { $_ => param ($_) } param();

The second line gets you the same result as

my %data; foreach my $param ( param() ) { $data{$param}= param($param); }

A call to param() (a function in the CGI module) in a list context gets you the name of all the parameters passed to the script via POST and GET. param("name") gets you the value of the passed "name" parameter.

HTH.

perl -e 'print "How sweet does a rose smell? "; chomp ($n = <STDIN>); +$rose = "smells sweet to degree $n"; *other_name = *rose; print "$oth +er_name\n"'

Replies are listed 'Best First'.
(Ovid) Re(2): use CGI
by Ovid (Cardinal) on May 24, 2001 at 23:09 UTC

    arturo wrote:

    my %data = map { $_ => param ($_) } param();

    While that will work for many cases, it fails with a query strings that have multiple values for a single name:

    color=blue&color=red

    There are two ways of resolving this. The first is map all hash keys to list references:

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

    Because param() uses wantarray, it will return a list if called in that context. Accessing param names with a single value become $data{'someval'}->[0]. Some people might think that's a bit weird, so one could also do the following:

    my %data = map { $_ => scalar @{[ param( $_ ) ]} == 1 ? param( $_ ) : +[ param( $_ ) ] } param;

    With the following query string...

    name=fred&color=red&color=blue

    ... the value for name can be accessed with $data{'name'} and the first value for color can be accessed with $data{'color'}->[0]

    I don't like the second method because there winds up being two methods for accessing similar data. This will likely cause problems in the long run. Further, with the multiple calls to param(), it's less efficient. However, I really don't like either method (though I've posted similar stuff before) because when I see people blindly pulling in all of that data, they tend not to untaint it.

    Cheers,
    Ovid

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

Re: Re: use CGI
by Anonymous Monk on May 24, 2001 at 23:05 UTC
    what exactly does:

    use CGI qw(:standard); my %data = map { $_ => param ($_) } param();


    that do? whatever it does it worked fine, thanks alot... I'd just like to understand what's going on
    heh