in reply to undef as a key in a hash.

undef will stringify as "" so they can be used as hash keys, equivalent to an empty string.

warnings will complain though:

perl -we'$b=undef;$a{$b}=1;print$a{""}' Use of uninitialized value in hash element at -e line 1. 1

update: strictly speaking a hash key (for a normal hash) can't be undef, a reference, an object or anything but a plain string, and using anything as a hash key that isn't a string will use the stringified form. Which explains the behaviour in TedYoung's example.

Replies are listed 'Best First'.
Re^2: undef as a key in a hash.
by ikegami (Patriarch) on Sep 25, 2007 at 19:20 UTC

    strictly speaking a hash key (for a normal hash) can't be undef, a reference, an object or anything but a plain string, and using anything as a hash key that isn't a string will use the stringified form.

    That's only true for plain hashes. Tied hashes are not subject to those restrictions, for example. (See code below.) Tied hashes can accept all of those as a key (including undef, although it generates a warning), but tied hashes can't have each/keys/values return undef because it's a sentinel value indicating all of the keys have been visited.

    So the question is whether there's another type of magical hash that can have keys return undef.

    use strict; use warnings; { package TestHash; sub keyinfo { my ($k) = @_; if (defined($k)) { if (ref($k)) { print("reference\n"); } else { print("string\n"); } } else { print("undefined\n"); } } sub TIEHASH { my ($c ) = @_; return bless([], $c); } sub FETCH { my ($s,$k ) = @_; keyinfo($k); return undef; } sub STORE { my ($s,$k,$v) = @_; keyinfo($k); push @$s, $k; } sub FIRSTKEY { my ($s ) = @_; return shift @$s; } sub NEXTKEY { my ($s ) = @_; return shift @$s; } } tie my %h, 'TestHash'; foreach my $k ('a', [], undef) { $h{$k} = 1; } print("\n"); foreach my $k ('a', [], undef) { my $dummy = $h{$k}; } print("\n"); foreach my $k (keys %h) { TestHash::keyinfo($k); }
    string reference Use of uninitialized value in hash element at line 29. undefined string reference Use of uninitialized value in hash element at line 31. undefined string reference