Perl   发布时间:2022-04-07  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了perl – 为什么在调用foo()||时,标量返回值死?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我刚刚花了一大堆时间调试一个问题,我已经追溯到了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().

你应该写出来

@H_605_2@my ( $one,$two ) = foo() or die $!;

或者运算符比赋值运算符更加松散,所以现在它的LHS是整个表达式my($one,$two)= foo(),而foo的上下文由列表赋值运算符确定,每个人都很高兴.

大佬总结

以上是大佬教程为你收集整理的perl – 为什么在调用foo()||时,标量返回值死?全部内容,希望文章能够帮你解决perl – 为什么在调用foo()||时,标量返回值死?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。