简体   繁体   中英

How is the scalar $keys getting value 1 instead of undef?

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM