7

这是代码:

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

如果我尝试这样称呼它:

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

我明白了Not enough arguments for MyPackage::function at x.pl line 5, near ""whatever" { "。我怎样才能调用它而不必sub在代码块前面添加?

4

2 回答 2

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";

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

“&”需要匿名子例程,如果作为第一个参数传递,则不需要“sub”关键字或后续逗号。
于 2010-03-04T18:58:01.447 回答
-3

这里,$& 是 Perl 的特殊变量,用于匹配精确的模式。(您在上下文中错误地使用了它) $` 用于匹配给定模式之前的字符串。$' 用于匹配给定模式之后的字符串。

于 2010-03-05T05:37:07.670 回答