views:

130

answers:

2

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?

+17  A: 
Sean
why doesn't it work when it's the first argument?
Geo
@Geo, it can work, but you need to be more explicit: `function( "whatever", sub { print "I'm inside the coderef\n" } );` The `name BLOCK EXPR` syntax only works if the coderef comes first.
friedo
Only because it was designed that way. I suspect the main reason for allowing it in the first place was to let users write subroutines that can be called like built-in functions that take a small snippet of code like map and grep, but anything more flexible could probably get confusing fast.
Sean
And it's something folks are working on. http://search.cpan.org/perldoc?PerlX::MethodCallWithBlock
Robert P
One reason why it would be problematic to have a block as a final argument is this: the parser expects an operator, not a term. There are some situations where two terms in a row are allowed, but they are difficulties for the parser.
Leon Timmermans
@Robert P => so now Perl can backport syntactic anomalies from Ruby :-/
Eric Strom
It's **Science!** Of course, with 5.12's parser hooks, it's going to be possible to do oh, so much more.
Robert P
@Robert P => sounds interesting, do you have any links that describe the new hooks?
Eric Strom
Sure do! Check out the 5.12 Perl Delta ( http://search.cpan.org/perldoc?perl5120delta ) document.
Robert P
A: 

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.

In the context in which the OP uses it, it's a function prototype. See http://perldoc.perl.org/perlsub.html#Prototypes
friedo