在 Perl 中,为什么在语句中添加“|| die”会导致它在标量上下文中求值?

In Perl why does adding "|| die" onto a statement cause it to evaluate in scalar context?

我终于发现我的代码是在标量上下文而不是列表上下文中进行评估的,即使我在赋值周围有 () 也是如此。

这是我演示问题的示例代码。

#!/usr/bin/perl
use strict;
use warnings;

use Data::Dumper qw(Dumper);

my $h1 = {
    var => "1",
    bar => "1",
    baz => "1",
};

my $h2 = {
    var => "2",
    bar => "2",
    baz => "2",
};

my $ds;
$ds->{rules} = [$h1,$h2];

print "TEST1\n";
print Dumper($ds);

print "TEST2\n";
my (@processes) = @{$ds->{rules}};
print Dumper(\@processes);
print "@processes\n";

print "TEST3\n";
(@processes) = @{$ds->{rules}} || die "unable to get rules form config.. \n";
print Dumper(\@processes);
print "@processes\n";

输出:

TEST2
$VAR1 = [
          {
            'bar' => '1',
            'baz' => '1',
            'var' => '1'
          },
          {
            'bar' => '2',
            'baz' => '2',
            'var' => '2'
          }
        ];
HASH(0x25eea68) HASH(0x260b240) 
TEST3
$VAR1 = [
          2
        ];
2

比较测试 2 和测试 3。据我所知,只需将 || die '.... ' 位添加到末尾就会改变语句在标量上下文中的求值方式,即使我在左侧有括号也是如此。 Q1:可能是我脑子比较笨,但为什么会这样呢?

Q2: 有没有"|| die ...." idiom/equivalent 做列表赋值时还能用的?

强制使用标量上下文的原因是 || binds stronger than =,所以

(@processes) = @{$ds->{rules}} || die "unable to get rules form config.. \n";

解析为

(@processes) = (@{$ds->{rules}} || die "unable to get rules form config.. \n");

并且 || 创建一个布尔上下文。然而 perl 有 a weakly binding version of ||:

(@processes) = @{$ds->{rules}} or die "unable to get rules form config.. \n";

将按您希望的方式进行解析。