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

Geo*_*Geo 7 perl reference coderef

这是代码:

sub function($&) {
    my $param1 = shift;
    my $code = shift;
    # do something with $param1 and $code
}
Run Code Online (Sandbox Code Playgroud)

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

function("whatever") {
    print "i'm inside the coderef\n";
}
Run Code Online (Sandbox Code Playgroud)

我得到Not enough arguments for MyPackage::function at x.pl line 5, near ""whatever" { ".如何在不必添加sub代码块前调用它?

Sea*_*ean 18

首先放入coderef参数:

sub function (&$) {
    my $code = shift;
    my $param1 = shift;
    # do something with $param1 and $code
}

function { print "i'm inside the coderef\n" } "whatever";
Run Code Online (Sandbox Code Playgroud)

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

"&"需要一个匿名子例程,如果作为第一个参数传递,则不需要"sub"关键字或后续逗号.

  • @Geo,它可以工作,但你需要更明确:`function("whatever",sub {print"我在coderef \n"}中);``name BLOCK EXPR`语法只有在coderef首先出现. (5认同)
  • 只因为它是这样设计的.我怀疑首先允许它的主要原因是让用户编写子程序,这些子程序可以被称为内置函数,它们需要一小段代码,如map和grep,但任何更灵活的东西都可能会让人感到困惑. (4认同)