Hi, I'm writing a program that uses a hash of hashes. At one point this program checks to see if a hash exists within a hash. Much to my suprise, checking for its existence caused that key to come into existence. Below is some sample code that illustrates what I'm talking about:

#!/usr/bin/perl -w use strict; use warnings; my %foo; if(exists($foo{qux})) { print "\$foo{qux} exists"; } if(exists($foo{bar}{baz})) { print "\$foo{bar}{baz} exists\n"; } if(exists($foo{bar})) { print "\$foo{bar} popped into existence\n"; } if(exists($foo{qux})) { print "\$foo{qux} popped into existence\n"; }

And it outputs: $foo{bar} popped into existence.

This is very confusing to me because I never did anything with $foo{bar} except check to see if it contained a reference to a hash (which I though was supposed to prevent autovivification).

My two questions are why does this happen (and why only with a hash of hashes) and how can I test for a hash within a hash without causing the key in question to come into existence?

Thanks!


In reply to Autovivification with hash of hashes by Mr_Person

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.