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)
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
subkeyword to create an anonymous subroutine that works fine as an argument in any position without a prototype.If you really really want to write it without the
subbut 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).