Sorry, this seems like such a basic question but I still don’t understand. If I have a hash, for example:
my %md_hash = ();
$md_hash{'top'}{'primary'}{'secondary'} = 0;
How come this is true?
if ($md_hash{'top'}{'foobar'}{'secondary'} == 0) {
print "I'm true even though I'm not in that hash\n";
}
There is no “foobar” level in the hash so shouldn’t that result in false?
TIA
Try a search on “Perl autovivification”.
The hash values “spring into existence” when you first access them. In this case, the value is
undef, which when interpreted as a number is zero.To test for existence of a hash value without auto-vivifying it, use the
existsoperator:Note that this will still auto-vivify
$md_hash{'top'}and$md_hash{'top'}{'foobar'}(i.e. the sub-hashes).[edit]
As tchrist points out in a comment, it is poor style to compare
undefagainst anything. So a better way to write this code would be:(Although this will now auto-vivify all three levels of the nested hash, setting the lowest level to
undef‘.)