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

coderef, perl, reference

Solution

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.

Problem

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?

Original source