Adam has asked for the wisdom of the Perl Monks concerning the following question:

Why does this line:
my %defaults = ref( $_[2+$[] ) ? %{$_[2+$[]} : {};
get this warning:
Reference found where even-sized list expected at script.pl line 125.
?? The line is the third line of a sub-routine that takes two or three arguments like this:
sub routine { my %override = %{$_[$[]}; # reference to a hash. my $var = $_[1+$[]; # scalar my %defaults = ref( $_[2+$[] ) ? %{$_[2+$[]} : {}; # optional hash + ref. #blah...
I only get the warning if there is no third argument. ref returns false when given undef, without any warnings as tested via:
prompt> perl -we "print ref( undef() ) ? 'y' : 'n'" n

Replies are listed 'Best First'.
Re: Reference found where even-sized list expected
by btrott (Parson) on Sep 13, 2000 at 23:55 UTC
    The ref isn't the problem. The problem is the curly braces, which create an anon hash reference; then you try to assign that to the %defaults hash. So you're assigning a reference, where an even-sized list (a list of key-value pairs) was expected. Hence the error message.

    Change that line to this:

    my %defaults = ref( $_[2+$[] ) ? %{$_[2+$[]} : ();
      Oh!!! ++ for btrott and jcwren

      Once again I fail to understand why someone would down vote a simple node like this one, which was merely posted to say, "Thank you for spotting that which I didn't." After all, isn't that what this site is about? I come here and answer other people's questions, why should I get down voted when I have a question and then take the time to thank the people that spotted the mistake? We all make mistakes. Even the saints and gurus amongst us.

(jcwren) Re: Reference found where even-sized list expected
by jcwren (Prior) on Sep 13, 2000 at 23:56 UTC
    Because the closing brace pair should be parens, since it's an empty hash.

    Update: Dang! btrott's answer faster AND better...

    --Chris

    e-mail jcwren