[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Omaha.pm] CGI.pm param() gotcha



On Oct 17, 2005, at 10:38 PM, Jay Hannah wrote:
20 bonus points to anyone who can tell me why I made this change:

<   $res->set_address    (
<      address1     => $q->param('gst_addr1'),
<      address2     => $q->param('gst_addr2'),
<      address3     => $q->param('gst_addr3'),
<      city         => $q->param('gst_city'),
<      state        => $q->param('gst_state'),
<      postal       => $q->param('gst_zipcode'),
<      country_code => $q->param('gst_country_code'));
---
  $res->set_address    (
     address1     => scalar($q->param('gst_addr1')),
     address2     => scalar($q->param('gst_addr2')),
     address3     => scalar($q->param('gst_addr3')),
     city         => scalar($q->param('gst_city')),
     state        => scalar($q->param('gst_state')),
     postal       => scalar($q->param('gst_zipcode')),
     country_code => scalar($q->param('gst_country_code')));

On Oct 18, 2005, at 7:28 AM, Kenneth Thompson wrote:
Because the first way sends scalar references into the passed hashref,
and the second sends scalar values into the passed hashref?

umm... maybe... -grin-

What I do know is that CGI.pm is pretty weird. In scalar context if a param is not set param() returns undef. In array context if a param is not set param() returns *an empty array*. In Perl empty arrays listed in arrays squish themselves out of existence automatically. Like so:

$ cat j.pl
print join "|", ( 1, 2, 3, ( ),   5, 6, "\n");
print join "|", ( 1, 2, 3, undef, 5, 6, "\n");
$ perl j.pl
1|2|3|5|6|
1|2|3||5|6|

Wacky huh?

In my example (and why I made the change) address3 was not set. Due to the array context of each param call in the top version, the hash got squished and address3 got set to "city". (See that -- the whole => list shifted up one! Doh!)

After the change, scalar context is explicit so address3 gets set to undef, city gets set to "Omaha", etc.

Does that make sense?

j