gpt4 book ai didi

perl - 为什么调用 foo() 时,wantarray 会在标量上下文中返回 ||死?

转载 作者:行者123 更新时间:2023-12-04 01:47:06 27 4
gpt4 key购买 nike

我刚刚花了很多时间调试一个我追溯到 wantarray() 的问题。 .我已将其提炼为这个测试用例。 (忽略 $! 在这种情况下不会有任何有用信息的事实)。我想知道为什么wantarray在第二个示例中,不认为它在 LIST 上下文中被调用:

#!/usr/bin/env perl

use strict;
use warnings;
use Test::More;

{
my ( $one, $two ) = foo();
is( $one, 'a', 'just foo' );
is( $two, 'b', 'just foo' );
}

{
my ( $one, $two ) = foo() || die $!;
is( $one, 'a', '|| die' );
is( $two, 'b', '|| die' );
}


done_testing();

sub foo {
return wantarray ? ( 'a', 'b' ) : 'bar';
}

这个测试的输出是:
$ prove -v wantarray.pl
wantarray.pl ..
ok 1 - just foo
ok 2 - just foo
not ok 3 - || die
not ok 4 - || die
1..4

# Failed test '|| die'
# at wantarray.pl line 15.
# got: 'bar'
# expected: 'a'

# Failed test '|| die'
# at wantarray.pl line 16.
# got: undef
# expected: 'b'
# Looks like you failed 2 tests of 4.
Dubious, test returned 2 (wstat 512, 0x200)
Failed 2/4 subtests

Test Summary Report
-------------------
wantarray.pl (Wstat: 512 Tests: 4 Failed: 2)
Failed tests: 3-4
Non-zero exit status: 2
Files=1, Tests=4, 0 wallclock secs ( 0.03 usr 0.01 sys + 0.02 cusr 0.00 csys = 0.06 CPU)
Result: FAIL

最佳答案

因为它没有在列表上下文中被调用。 ||在其左侧施加标量上下文,在这种情况下,其左侧是表达式 foo() .

你应该改写

my ( $one, $two ) = foo() or die $!;
or运算符比赋值运算符绑定(bind)得更松散,所以现在它的 LHS 是整个表达式 my ($one, $two) = foo() , 和 foo的上下文是由列表赋值运算符决定的,大家都很开心。

关于perl - 为什么调用 foo() 时,wantarray 会在标量上下文中返回 ||死?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17536311/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com