Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Why does testing for the existence of hash keys create the keys ?

by fshrewsb (Acolyte)
on Oct 08, 2012 at 08:00 UTC ( #997763=perlquestion: print w/replies, xml ) Need Help??
fshrewsb has asked for the wisdom of the Perl Monks concerning the following question:

This is very simple, but it happens often and I have to write extra code to handle it :

use Data::Dumper; my $hashref; print Dumper $hashref; if(exists $hashref->{a}->{b}) { # Do something } print Dumper($hashref);

Of course, at the first print $hashref is undef, but after the exists statement $hashref is now: { 'a' => {} } Why ?

Replies are listed 'Best First'.
Re: I just want to understand why ...
by Athanasius (Chancellor) on Oct 08, 2012 at 08:18 UTC

    From exists:

    Although the most deeply nested array or hash element will not spring into existence just because its existence was tested, any intervening ones will.

    This is called autovivification. There is a good explanation of autovivification at

    Hope that helps,

    Athanasius <°(((><contra mundum

Re: I just want to understand why ...
by 2teez (Priest) on Oct 08, 2012 at 08:19 UTC
Re: I just want to understand why ...
by Anonymous Monk on Oct 08, 2012 at 08:35 UTC

      And then there's the third way which requires some extra typing, but is fine for two-level or three-level hashes:

      my $r = $hashref; # better to use a short variable name here if($r->{a} and $r->{a}->{b} and exists $r->{a}->{b}->{c}) { # Do something }
      No autovivification.


      18:58 >perl -w -Mstrict -MData::Dumper -E "my $foo; say Dumper($foo); +if (exists $foo->{bar}{anything}{you}{want} ) { say 'hi' } say Dumper +($foo);" $VAR1 = undef; $VAR1 = { 'bar' => { 'anything' => { 'you' => {} } } }; 19:00 >

      Looks like 3 levels of autovivification to me.


      Update: See below.

      Athanasius <°(((><contra mundum

        And where is no autovivification; in your code?
        لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: I just want to understand why ...
by parv (Priest) on Oct 09, 2012 at 07:47 UTC
    Could you change the title from being useless to "Understanding creation of missing keys" or similar?

      Point taken about the title ! Thanks all. I had not encountered the term "autovivification" before.

      no autovivification qw(exists);

      should solve my problems without creating new ones !

        Much appreciate the changed title.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://997763]
Approved by Athanasius
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (8)
As of 2016-10-28 11:09 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (381 votes). Check out past polls.