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.