标量或数组函数

Mat*_*usz 2 arrays perl scalar function

我必须执行将作为标量和数组工作的函数。例如:

@t = testfunc(1, 2, 3, 4);
$x = testfunc(1, 2, 3, 4);
Run Code Online (Sandbox Code Playgroud)

有人知道我该怎么做吗?如果是 $x,则必须打印“标量”;如果是 @t,则必须打印“数组”。我尝试做这样的事情:

sub testfunc()
{
   print "test";
}
Run Code Online (Sandbox Code Playgroud)

但即使这样也行不通:/

PSI*_*Alt 5

此功能称为“调用上下文”。使用wantarray关键字。

@t = testfunc(1, 2, 3, 4);
$x = testfunc(1, 2, 3, 4);
sub testfunc {
    if ( wantarray ) {
        print "List context\n";
    }
    # False, but defined
    elsif ( defined wantarray ) {
        print "Scalar context\n";
    }
    # False and undefined
    else {
        print "Void context\n";
    }
}
Run Code Online (Sandbox Code Playgroud)


Sob*_*que 5

perl 中有一个名为的函数,wantarray它返回:

  • true如果在列表上下文中调用子函数
  • false如果标量
  • undef如果两者都不是。

举个例子:

use strict;
use warnings;

sub wantarray_test {

    if ( not defined wantarray() ) {
        print "Called in void context by ", caller(), "\n";
    }
    else {
        if ( wantarray() ) {
            print "Called in list context by ", caller(), "\n";
            return ( "A", "list", "of", "results" );
        }
        else {
            print "called in a scalar context by ", caller(), "\n";
            return "scalar result";
        }
    }

}

my @result = wantarray_test();
print "@result\n";

my $result = wantarray_test();
print $result, "\n";

wantarray_test();
Run Code Online (Sandbox Code Playgroud)

奖金问题:

如果您满足以下条件,您认为您会得到什么:

print wantarray_test();
Run Code Online (Sandbox Code Playgroud)

如果您愿意的话,您甚至可以做更多的事情Contextual::Return- 这将允许您测试更详细的上下文,例如scalar和之间的差异boolean。(例如,如果您想测试百分比,这很有用 - 您可能不想将“0”视为“假”)。

但要小心上下文相关的函数。很容易产生一些意想不到的行为,这可能会给你带来严重的后果。

作为一个相关的说明 - 你不应该以你现有的方式声明你的子程序。Perl 中有一种称为原型的机制,它定义子例程期望的参数类型。看:perlsub。您不应该将您的子定义为:

sub testfunc() 
{   
     # some stuff
}
Run Code Online (Sandbox Code Playgroud)

这指定了一个原型,应该避免,除非您确定这就是您想要的。

  • 添加一些关于 OP 的糟糕原型的内容 (4认同)