Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Why does perl expression in empty nested hash create parents

by furry_marmot (Pilgrim)
on Feb 21, 2011 at 19:23 UTC ( #889475=note: print w/ replies, xml ) Need Help??


in reply to Why does perl expression in empty nested hash create parents

Sadly, it's a feature, but it's the intermediate keys you are creating. Try this:

print "1st run\n" if exists $a{a}; print "2nd run\n" if exists $a{a}{b}{c}; print "3rd run\n" if exists $a{a}; # prints 3rd run
$a{a}{b} is created in order to test the existence of $a{a}{b}{c}. From perldoc -f exists:
Note that the EXPR can be arbitrarily complicated as long as the final operation is a hash or array key lookup or subroutine name: if (exists $ref->{A}->{B}->{$key}) { } if (exists $hash{A}{B}{$key}) { } if (exists $ref->{A}->{B}->[$ix]) { } if (exists $hash{A}{B}[$ix]) { } if (exists &{$ref->{A}{B}{$key}}) { } Although the mostly deeply nested array or hash will not spring into existence just because its existence was tested, any intervening ones will. Thus "$ref->{"A"}" and "$ref->{"A"}->{"B"}" will spring into existence due to the existence test for the $key element above. This happens anywhere the arrow operator is used, including even here: undef $ref; if (exists $ref->{"Some key"}) { } print $ref; # prints HASH(0x80d3d5c) This surprising autovivification in what does not at first--or even second--glance appear to be an lvalue context may be fixed in a future release.
But you can be smart about this. You can test for $a{a}. If it doesn't exist, any and all subkeys certainly won't exist.

--marmot


Comment on Re: Why does perl expression in empty nested hash create parents
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (11)
As of 2014-09-23 11:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (219 votes), past polls