in reply to undef as a key in a hash.

I had to try this myself, because I couldn't believe it:

$a{undef} = 1; print defined for keys %a; # Output 1 # This doesn't work either: %a = (undef, 1);

I wonder what he was thinking...

Ted Young

Replies are listed 'Best First'.
Re^2: undef as a key in a hash.
by Joost (Canon) on Sep 25, 2007 at 18:45 UTC
Re^2: undef as a key in a hash. (constant.pm "bug")
by lodin (Hermit) on Sep 26, 2007 at 12:05 UTC

    I wonder what he was thinking...

    The hash-style usage of constant wasn't added until perl 5.7.1, and the defined $name check was around before that. Basically all of 5.7.0's code was kept intact and put in the for loop. The defined $name check was just accidentally (I presume) left inside the for loop.

    Here's how it should look.

    my $multiple = ref $_[0]; if ( $multiple ) { ... } else { unless (defined $_[0]) { require Carp; Carp::croak("Can't use undef as constant name"); } $constants{+shift} = undef; } foreach my $name ( keys %constants ) { ... }
    Not that this matters much, because
    use constant undef, 'x';
    will fail anyway. You just get a slightly less clear error message.

    lodin