开发者

Why am I getting a syntax error when I pass a coderef to this prototyped Perl subroutine?

This is the code:

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

If I try to call i开发者_运维问答t like this:

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

I get Not enough arguments for MyPackage::function at x.pl line 5, near ""whatever" { ". How can I call it without having to add sub in front of the code block?


Put the coderef argument first:

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

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

See the perlsub man page, which reads in part:

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


Here, $& is a Perl's special variable which is used to match the exact pattern. (you have wrongly used it in your context) $` is used to match the string before the given pattern. $' is used to match the string after the given pattern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜