开发者

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

开发者 https://www.devze.com 2022-12-22 10:16 出处:网络
This is the code: sub function($&) { my $param1 = shift; my $code = shift; # do something with $param1 and $code

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

精彩评论

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

关注公众号