I'm trying to get this clear in my brain so I can explain it to a bunch of folk who have never seen Perl before...

I seemed to recall a long while ago that if you accessed a hash element that didn't exists it would autovivify the element... even if testing it with defined, and that you want to use exists... but looking through current documentation it seems that some of that warning has been curtailed. So I'm a little foggy as to what is the warning related to creating unintended hash keys and autovivification. Sorry if I'm really vague about version #'s and details... I may have misremembered things.

Are there conditions in which you can still create autovivified hash keys with undefined values that you never intended to do? And what is the way to avoid that now with current versions of Perl?

I wrote a little script to test it, because I thought this used to fail.

print "Oh No!(1)" if $rec{NOTE} eq "Beware!"; print "Oh No!(2)" if exists $rec{NOTE};
I don't get either "Oh No!" comments. I thought once upon a time it did... But with Nested Hashes I still get the intermediate hash autovivified.
print "Oh No!(3)" if exists $rec{NOTE}{Nested}; print "Oh No!(4)" if exists $rec{NOTE}; OUTPUT: Oh No! (4)

So I guess if you have nested Hashes it creates an empty hash pointer for the NOTE key.


In reply to gotchas with hash element autovivification by raybies

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.