Because autovivifying will assign a "default value" of undef when you do not supply an assignment (rhs) value as part of the autovivifying expression.

In your first example, the enclosure within  %{...} requires that the enclosed expression must yield a reference to a hash (not doing so is an error), and of course, undef cannot be interpreted as a hash ref.

In your second example, the "keys()" function is only looking at keys in the hash, not at values, so it doesn't matter that the "default value" being assigned to $h{x} happens to be undef.

UPDATE: When I first wrote and posted the above, it seems I was missing an important point, and I think GrandFather came closer to getting it right in his reply below: there is something "DWIM-ishly" odd going on with the keys() function, and I personally cannot explain why the second snippet in the OP does not trigger an error. On reflection, it strikes me as strange, and I understand jrw's continuing sense of confusion. (But ikegami and shmem have helped a lot with their replies, and I am less confused now.)


In reply to Re: Keys() required to autovivify? by graff
in thread Keys() required to autovivify? by jrw

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.