Reputation:
Folks,
As far as my understanding goes, exists
function would check for existence of a key in a hash. So for the below mentioned situation, key1
or key2
have not been defined. Going by that the hash reference $var
has no keys.
In which case upon calling keys(%{$var})
should return undef.
HOWEVER, its returning 1. How..what am I missing here ?
my $var;
if (exists $var->{key1}->{key2}) {
$var->{key1}->{key2} = 1;
}
my $keys = keys(%{$var});
print $keys; #prints 1 to output console
Upvotes: 0
Views: 146
Reputation: 50304
This is autovivification. Note that you can disable autovivification for your whole script, or for a particular lexical scope, by using the no autovification; pragma.
Upvotes: 0
Reputation:
The fact that you're checking $var->{key1}->{key2} creates $var->{key1} as empty hashref. This can be seen by doing:
use Data::Dumper;
my $var = {};
if (exists $var->{key1}->{key2}) {
print "cannot happen\n"
}
print Dumper($var);
Which prints:
$VAR1 = {
'key1' => {}
};
So, the scalar of keys is 1, because there is one key.
Upvotes: 3