如果Perl中的哈希不存在,则添加密钥 [英] Hash in Perl adds key if it does not exist

查看:331
本文介绍了如果Perl中的哈希不存在,则添加密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下perl脚本,该脚本将一些详细信息存储在哈希中.在填充了哈希中的某些条目之后,我将打印哈希的内容,从而产生以下输出

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

此后,我尝试获取哈希中不存在的hey(我的$ nm = $ components {'11:Name11'} {'name'});

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

此检查之后,如果我打印哈希的内容,我看到上面的键(即"11:Name11")已添加到哈希中(突出显示在下面).有人可以解释这种行为吗?

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"
}

谢谢.

推荐答案

这称为 autovivification .这是Perl的一项功能,它允许您使用以前未声明或初始化的哈希元素.每当取消引用未定义的值(如$components{'11:Name11'})(在Perl尝试评估$components{'11:Name11'}{'name'}时发生),就会发生这种情况.

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'}).

有一个 autovivification 编译指示,您不能使用它来禁用此行为.

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"}
    ...
}

这篇关于如果Perl中的哈希不存在,则添加密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆