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.


In reply to (Ovid) Re(2): use CGI by Ovid
in thread making a hash from cgi parameters by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.