[Melbourne-pm] just my opinion

Toby Corkindale tjc at wintrmute.net
Mon Sep 22 18:27:30 PDT 2008


On Fri, Sep 19, 2008 at 09:23:35AM +1000, Jacinta Richardson wrote:
> Toby Corkindale wrote:
> 
> > What would you expect the output of the following script to be?
> > 
> > --------
> > my %foo = (
> >     undef => 'null',
> >     foo   => 'bar',
> >     qux   => 'qaaz'
> > );
> > print join(' ', @foo{qw(undef foo qux)}) . "\n";
> > --------
> 
> Exactly what it is.  "null bar qaaz".  It doesn't make any sense to have an
> undefined hash key (in fact Perl will complain under warnings if you try hard
> enough (Use of uninitialized value in list assignment at - line 1.)).
> Furthermore => is just like , *except* that it quotes any whole word to its
> left.  Thus the first key there is 'undef' not a call to the function undef().
> Use undef() if that's what you mean.

I understand why it is done, but I think it is confusing to people, eg:
---------
my %foo = ( undef => 'null' );
say 'Hash val of undef is: ' . $foo{undef}; # prints null
my $key;
say "My key is " . (defined $key ? 'defined' : 'undef'); # prints undef
say "My key's hash val is: " . $foo{$key}; # prints nothing, and warns.
----------

But that said, not that many people probably hit it anyway.. As you say, undef
is a silly thing to hash.

In my original example I also used a hash slice: @foo{qw(undef foo qux)}
Aside from the use of undef there, I think hash vs array slices are again a tad
confusing to the newcomer too, eg:
-----------
my %foo = qw( maria trans cat mat );
my @foo = ( socks => 'jocks', moon => 'gruyere' );
say @foo{qw(maria cat)};
say @foo[-1, 2];
%foo = @foo;
my $ref = \%foo;
say @$ref{qw(moon socks)};
-----------
(Mind you, I'd shoot anyone who actually tried to submit code written that way)

It makes sense if you remember that substituting a $ sigil in front of a
variable converts it into returning a scalar, and that smushing a snail on its
forehead makes it return arrays, but the way the names appear to overlap with
existing variables can throw people.

tjc

-- 
Turning and turning in the widening gyre/The falcon cannot hear the falconer;
Things fall apart, the centre cannot hold/Mere anarchy is loosed upon the world
(gpg --recv-key B1CCF88E)


More information about the Melbourne-pm mailing list