我正在重构我继承的 Perl 程序。下面一行
(! exists $self->{DEVEL}) && { @$d = $nsaobj->filter_list(@$d) };
抛出以下警告...
Useless use of anonymous hash ({}) in void context...
首先我想了解这里发生了什么。我是否正确,这只是下面语句的另一种书写方式?
if (! exists $self->{DEVEL}) {
@$d = $nsaobj->filter_list(@$d);
}
我最好的猜测是,原来的行是由于惰性求值而起作用的,如果是这样,那么这样写的合理性是什么?
第二,为什么这一行会抛出“无用的使用..”警告?
最佳答案
First I want to understand what is happening here. Am I correct that this is just a different way of writing the statement below?
是的,这似乎是原始代码的意图,但这并不完全是它正在做的事情。 Perl 的警告是正确的。原作者可能想写
(! exists $self->{DEVEL}) && do { @$d = $nsaobj->filter_list(@$d); };
do
是这里的重要部分,因为它声明执行后续 block 。如果没有 do
,Perl 会使用 @$d
的内容创建一个匿名哈希引用,但该值不会绑定(bind)到任何变量,因此会出现警告。如果 @$d
最终成为具有奇数个元素的数组,甚至可能导致运行时错误。
如果希望将其保留为一句台词,这将是一个更典型的结构
@$d = $nsaobj->filter_list(@$d) unless exists $self->{DEVEL};
关于perl - 为什么此代码会引发 "Useless use of anonymous hash ({}) in void context"警告。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24535354/