Hash in Perl adds key if it does not exist

2019-07-02 19:01发布

I have the following perl script which is storing some details in a hash. After populating some entries in the hash, I'm printing the content of the hash which produces the following output

Key:4:Name4 Value:Name4
Key:3:Name3 Value:Name3
Key:2:Name2 Value:Name2
Key:1:Name1 Value:Name1
Key:0:Name0 Value:Name0

After that I am trying the get search for a hey which does not exist in the hash (my $nm = $components{'11:Name11'}{'name'} );

After this check If I print the content of hash, I see that above key (i.e '11:Name11') is getting added to hash (highlighted below). Can someone explain this behavior please?

Key:4:Name4 Value:Name4
Key:3:Name3 Value:Name3
**Key:11:Name11 Value:**
Key:2:Name2 Value:Name2
Key:1:Name1 Value:Name1
Key:0:Name0 Value:Name0

my %components ;

for ($i=0;$i<5;$i++)
{
    my $hash = {} ;
    my $vr = $i+100;
    $hash->{'container'} = $i ;
    $hash->{'name'} =  'Name'.$i;
    $hash->{'version'} = $vr ;
    my $tmpCompName = $hash->{'container'}.':'.$hash->{'name'};
    $components{$tmpCompName} = $hash ;
}


while (my ($k,$v)=each %components){
        print "Key:".$k." Value:".$v->{'name'}."\n";
}

my $tmp = '11:Name11';

my $nm = $components{$tmp}{'name'} ;

print "Name:".$nm."\n";

print "After check\n";

while (my ($k,$v)=each %components){
            print "Key:".$k." Value:".$v->{'name'}."\n"
}

Thanks in advance.

标签: perl hash
1条回答
姐就是有狂的资本
2楼-- · 2019-07-02 19:13

This is called autovivification. It is a feature of Perl that allows you to use a hash element that you haven't previously declared or initialized. It occurs whenever an undefined value (like $components{'11:Name11'}) is dereferenced (which happens when Perl tries to evaluate $components{'11:Name11'}{'name'}).

There is a autovivification pragma that you can unuse to disable this behavior.

{
    no autovivification;
    if ($hash{"non-existent-key"}{"foo"}) {  # won't create $hash{"non-existent-key"}
    ...
}
查看更多
登录 后发表回答