Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 it 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?

like image 328
Geo Avatar asked Mar 04 '10 18:03

Geo


1 Answers

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.
like image 132
Sean Avatar answered Sep 22 '22 07:09

Sean