I don't get the symptoms you describe, although I had to alter your code to get it to compile:
use strict; use warnings; use Data::Dumper; my $hash; $hash = {A => { LEVEL1 => { LEVEL1_2 => { LEVEL1_2_3 => { VAL => 'somevalue' } } } } }; for (my $i = 0; $i< 3; $i++) { if (defined $hash->{A}->{LEVEL2}->{LEVEL2_2}) { # do something print "if branch\n"; } elsif (defined $hash->{A}->{LEVEL1}->{LEVEL1_2}) { #do something print "elsif branch\n" } else { print "else branch\n" } } print Dumper($hash);
gives:
elsif branch elsif branch elsif branch $VAR1 = { 'A' => { 'LEVEL1' => { 'LEVEL1_2' => { 'LEVEL1_2_3' => { 'VA +L' => 'somevalue' } } }, 'LEVEL2' => {} } };
The key 'LEVEL2' is added by autovivification as described by Anonymous Monk, but not 'LEVEL2_2' as you imply, so it does not go through the 'if'. Could you post some code that compiles and shows the problem you have?
I'm not sure if this is relevant, but if you want to check for the existence of a key use exists, defined checks for the existence of a value.

In reply to Re: usage of if on nested hash creating empty slot for non existing value by cdarke
in thread usage of if on nested hash creating empty slot for non existing value by rakeshrocks

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.