yogibimbi
yogibimbi

Reputation: 607

Is it possible to prototype a subroutine as $$& in perl?

Just a curiosity, I have played around with prototyping a bit, but it seems that the prototype & for a subroutine is only allowed in the first position.

When I write

sub test (&$$) {
    do_something;
}

and call it as

test {doing_something_else} 1,2;

it works.

When I prototype like this

sub test ($$&) {
    do_something;
}

and again call it as

test 1,2 {doing_something_else};

it doesn't work. I tried with various permutations, but nothing seems to deliver.

Am I missing something, or is it not possible? And if not, why?

(I maybe need to specify, that I successfully tried the option of calling test(1, 2, sub{foo}), of course, but it doesn't look quite as sexy as the option in the last example above (and for that I don't even need prototyping); I would like to be able to implement the syntax of structures like if () {} else {}, etc. or, more to the point, try () catch () {} or switch () case (){}, but I guess that's why those constructs have not yet been implemented in Perl)

Upvotes: 2

Views: 166

Answers (2)

choroba
choroba

Reputation: 242123

Quoting the documentation (perldoc perlsub):

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

Upvotes: 7

Eric Strom
Eric Strom

Reputation: 40152

The & prototype character only takes the block form when it is the first item in a prototype. This is just a limitation of the way perl's prototype parser works.

You could always use the sub keyword to create an anonymous subroutine that works fine as an argument in any position without a prototype.

test 1, 2, sub {doing_something_else};

If you really really want to write it without the sub but not in the first position, you could have fun playing around with Devel::Declare to write your own parse rules for the test subroutine (this is an advanced topic).

Upvotes: 8

Related Questions