http://www.perlmonks.org?node_id=229910

Mr_Person has asked for the wisdom of the Perl Monks concerning the following question:

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!