http://qs1969.pair.com?node_id=11113067


in reply to "print" of nonexistent element is actually altering a hash

What you're seeing is the effect of "autovivification". It's not the print that's doing this, it's the hash access. $hash{'key0'}{'key1'} means you're asking Perl what's stored in the hashref at the key key0 in %hash, but since that doesn't exist, Perl infers from $hash{key0}{...} that you want $hash{key0} to be a hashref, so it creates it for you. The same thing happens a level deeper at $hash{'key0'}{'key1'}{'key2'} - note how it doesn't create key2 for you.

If you want to avoid this in core Perl, then first note that autovivification, as a rule of thumb, happens in "lvalue" context, that is, in places where a value could be assigned to the hash. This is true in sometimes surprising contexts, such as for loops, because the loop variable is an alias to the values being looped over. If you want to avoid autovivification in such places, you need to use exists to check for the existence of hash keys before accessing them. An alternative is to use no autovivification from CPAN.