Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: "print" of nonexistent element is actually altering a hash

by haukex (Archbishop)
on Feb 17, 2020 at 18:19 UTC ( #11113067=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11113067]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (8)
As of 2022-11-30 20:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?