Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: usage of if on nested hash creating empty slot for non existing value

by Anonyrnous Monk (Hermit)
on Jan 29, 2011 at 09:36 UTC ( [id://885005]=note: print w/replies, xml ) Need Help??


in reply to usage of if on nested hash creating empty slot for non existing value

I am not able to understand why an empty slot is created.

The feature is called "autovivification".

When you dereference a non-existing element, such as {LEVEL2}->{LEVEL2_2}, the element (the LEVEL2 hashref entry here) is automagically being created as needed.

#!/usr/bin/perl -w use strict; my $var; if (defined $var->{FOO}->{BAR}) { print "found" } use Data::Dumper; print Dumper $var; __END__ $VAR1 = { 'FOO' => {} };

Here, in order to check if the entry BAR is defined, a hash(ref) with an entry FOO is being created. The value associated with the entry FOO is created as another hash(ref) which could potentially hold the checked-for entry BAR.

You might argue this doesn't make sense when just testing for existence or definedness, but that's the way it's currently implemented.  See the threads turned up by the above google search for more in-depth discussion.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2025-03-27 16:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    When you first encountered Perl, which feature amazed you the most?










    Results (70 votes). Check out past polls.

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.