
Null right hand comma operand in hash assignment
Quote:
> The hash assignment at the bottom of this code did not do what I
> expected if the CGI parameters did not return values:
> #
> use strict;
> use CGI;
> my $query = new CGI;
> my %context =
> (
> origin => $query->param('origin'),
> record => $query->param('consultID')
> );
> #
> I planned on subsequent processing depending on the boolean context of
> $context{'origin'}, but in the scenario where the CGI parameters did
> not return values, $context{'origin'} contained the value 'record'. I
> 'fixed' this as follows:
> #
> my %context =
> (
> origin => $query->param('origin') || undef,
> record => $query->param('consultID') || undef
> );
> #
> I read the entry for the comma operator in the docs (i.e. I now know
> that => is called 'digraph'), and also did a google search, but
> nothing jumped out at me, plus I left my Camel book at home. I'm
> wondering:
> A) if anybody can explain this behavior, and/or
> B) can anybody suggest a more efficient way to assign to my %context
> hash
> Perhaps I missed something in the docs?! (I read them though: I even
> learned that => is the 'digraph')
It actually has nothing to do with the "fat comma"; replacing the "=>"
with commas (and quoting the names before them) leads to the same result.
The problem is that when you call subs or methods from inside a list
assignment (such as you're using to initialize %context with), they're
called in list context. Now when you look at the code for param() in
CGI.pm, you'll see that the next-to-last line is:
return unless defined($name) && $self->{$name};
and when return is invoked with no argument, the sub or method returns
undef if it was called in scalar context, but an *empty list* if it was
called in list context. So in your case, the assignment actually works
out to:
my %context = ('origin', , 'record', $query->param('consultID'));
at which point it becomes apparent that when Santa checks his list twice,
he's gonna find out you've been {*filter*} not nice, because if you
had enabled warnings you'd have gotten one about trying to assign an odd
number of elements to a hash. But since you didn't, your thinking got
focused on the wrong thing (the behavior of =>) and you were led on a wild
goose chase.