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

If I am defining a hash and instead of typing:

%hash = ( '1' => 'a', '2' => 'b' );

I accidentally type:

%hash = ( '1' => => 'a', '2' => 'b' );

Why doesn't $hash{'1'} end up being undef?

Thanks!

Replies are listed 'Best First'.
Re: Why don't extra arrows in a list screw up hash creation?
by VSarkiss (Monsignor) on Dec 08, 2004 at 21:46 UTC

    So sayeth perldata:

    LISTs do automatic interpolation of sublists....

    The null list is represented by (). Interpolating it in a list has no effect. Thus ((),(),()) is equivalent to (). ...

    This interpolation combines with the facts that the opening and closing parentheses are optional (except when necessary for precedence) and lists may end with an optional comma to mean that multiple commas within lists are legal syntax. The list 1,,3 is a concatenation of two lists, 1, and 3, the first of which ends with that optional comma. 1,,3 is (1,),(3) is 1,3 (And similarly for 1,,,3 is (1,),(,),3 is 1,3 and so on.) Not that we'd advise you to use this obfuscation.

    Combined, of course, with the knowledge that the => is just a comma that quotes its LHS explains it.

    Update
    Expanded the quote to make it clearer.

Re: Why don't extra arrows in a list screw up hash creation?
by davido (Cardinal) on Dec 08, 2004 at 21:43 UTC

    It's DWIMery in action. The => fat comma works the same way a comma works with respect to empty args. In other words, @array = ( 1 ,, 2, 3 ); creates a three elemnt list too (not four). If you want an undef element spell it out: undef.


    Dave