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

In reply to Re^2: undef as a key in a hash. by ikegami
in thread undef as a key in a hash. by fenLisesi

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.