使用'exists'进行额外的哈希查找? [英] Additional hash lookup using 'exists'?

查看:144
本文介绍了使用'exists'进行额外的哈希查找?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  if(exists $ ids {$ name}){
$ id = $ ids {$ name};
}

这是不错的做法吗?我有点担心它包含两个查找,其中应该完成一个。有没有更好的方法来检查存在和赋值?

解决方案

通过检查存在,您可以防止自动版本化。请参阅 Autovivification:它是什么,为什么我在乎?



更新:由于以下 trendels 指出,autovivification在您发布的示例中不起作用。我假设实际的代码涉及多级哈希。



下面是一个例子:

 #!/ usr / bin / perl 

use strict;
使用警告;

使用Data :: Dumper;

my(%hash,$ x);

if(exists $ hash {test} - > {vivify}){
$ x = $ hash {test} - > {vivify} - > {now};
}

打印Dumper \%hash;

$ x = $ hash {test} - > {vivify} - > {now};

打印Dumper \%hash;

__END__


C:\Temp> t
$ VAR1 = {
'test'=> {}
};
$ VAR1 = {
'test'=> {
'vivify'=> {}
}
};


I sometimes access a hash like this:

if(exists $ids{$name}){
    $id = $ids{$name};
}

Is that good practice? I'm a bit concerned that it contains two lookups where really one should be done. Is there a better way to check the existence and assign the value?

解决方案

By checking with exists, you prevent autovivification. See Autovivification : What is it and why do I care?.

UPDATE: As trendels points out below, autovivification does not come into play in the example you posted. I am assuming that the actual code involves multi-level hashes.

Here is an illustration:

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

my (%hash, $x);

if ( exists $hash{test}->{vivify} ) {
    $x = $hash{test}->{vivify}->{now};
}

print Dumper \%hash;

$x = $hash{test}->{vivify}->{now};

print Dumper \%hash;

__END__


C:\Temp> t
$VAR1 = {
    'test' => {}
};
$VAR1 = {
    'test' => {
        'vivify' => {}
    }
};

这篇关于使用'exists'进行额外的哈希查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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