我刚刚花了一大堆时间调试一个问题,我已经追溯到了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,'|| die' ); is( $two,'|| 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 $!;
或者运算符比赋值运算符更加松散,所以现在它的LHS是整个表达式my($one,$two)= foo(),而foo的上下文由列表赋值运算符确定,每个人都很高兴.