当我将coderef传递给这个原型Perl子例程时,为什么会出现语法错误?

前端之家收集整理的这篇文章主要介绍了当我将coderef传递给这个原型Perl子例程时,为什么会出现语法错误?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是代码
sub function($&) {
    my $param1 = shift;
    my $code = shift;
    # do something with $param1 and $code
}

如果我试着像这样打电话:

function("whatever") {
    print "i'm inside the coderef\n";
}

我在x.pl第5行得到MyPackage :: function的参数不足,接近“”无论“{”.如何在不必在代码块前添加sub的情况下调用它?

解决方法

首先放入coderef参数:
sub function (&$) {
    my $code = shift;
    my $param1 = shift;
    # do something with $param1 and $code
}

function { print "i'm inside the coderef\n" } "whatever";

请参阅perlsub手册页,其中部分内容如下:

An “&” requires an anonymous subroutine,which,if passed as the first argument,does not require the “sub” keyword or a subsequent comma.

原文链接:https://www.f2er.com/Perl/171978.html

猜你在找的Perl相关文章