I have a nested hash table that looks like this:
my %myhash = (
"val1" => {
"A/B.c" => {
"funct1" => 1
}
},
"val2" => {
"C/D.c" => {
"funct2" => 1
}
}
)
My objective with this data structure is to produce different values based on whether certain hash tables exist. For example,
sub mysub
{
my $val = shift;
my $file = shift;
my $funct = shift;
if (exists $myhash{$val}{$file}{$funct}) {
return "return1";
}
if (exists $myhash{$val}{$file}) {
return "return2";
}
return "return3";
}
The behavior I’m encountering is as follows. I have an instance in time when
my $val = “val1”;
my $file = “C/D.c”;
my $funct = “funct3”;
At this point in time, the return value I get “return2”. These are my observations with the Perl debugger:
- Break at first “if” in mysub
- Print p $proxToBugs{“val1”}{“C/D.c”} ==> Returns blank line. Okay. Continue and this “if” is skipped.
- Continue and break at the second “if” in mysub
- Print p $proxToBugs{“val1”}{“C/D.c”} ==> Returns “HASH(0x…)”. WTF moment. Function returns “return2”.
This tells me that running the first if modified the data structure, which allows the second if to pass when in fact it shouldn’t. The function I’m running is identical to the function shown above; this one is just sanitized. Anyone has an explanation for me? 🙂
Yes. This is because of autovivification. See the bottom of the
existsdocumentation:Where “…test for the $key element above…” refers to:
Happy coding.