in reply to Re: undef as a key in a hash.
in thread undef as a key in a hash.

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