Perl:测试哈希切片不会产生预期的结果

Perl: testing hash slice doesn't produce expected outcome

我有以下代码:

if (defined(@hash{qw{value1 value2 value3}})){
    # code block
}

如果定义了 $hash{value1}、$hash{value2} 或 $hash{value3},我想要执行的是代码块。但是,当且仅当定义了 $hash{value3} 时代码块才会执行:

$hash{value3}='yep, here!';
if (defined(@hash{qw{value1 value2 value3}})){
    print "yay!";
}

输出:

yay!

但是:

$hash{value2}='yep, here!';
if (defined(@hash{qw{value1 value2 value3}})){
    print "yay!";
}

输出:

<nothing>

为什么这不能正常工作,我应该怎么办?

perldoc -f defined没有提到hash slice,警告也没有警告你这个,但是你想要的是,

if (grep defined, @hash{qw{value1 value2 value3}}) {
  # code block
}

因为 defined() 强制标量上下文,并且 切片 在这种情况下 return 最后一个元素。

use warnings;

sub context {
  print wantarray ? "LIST" : "SCALAR";
}

my $def = defined(context());

输出SCALAR