You could just eval
the blocks
use experimental 'signatures';
use feature 'say';
sub doublethecode ($block1, $block2) { eval { $block1; }; eval { $block2;} } ;
doublethecode \&{ print "OH " }, \&{ say for qw/HAI YOU LOLCAT :-P/ };
output:
OH, HAI
YOU
LOLCAT
:-P
Then just ignore the \&
and you're there.
As of v5.20
You can use signatures and :prototype
attributes together. The signatures
feature gives a more "common" syntax and a minimalist sort of argument checking. Maybe one day a future perl will have a "builtin" (optional, highly flexible) type system of some kind to go with it, but prototypes aren't anything like that right now. So something like:
sub doublethecode :prototype(\&\&) ($cr1, $cr2) { $cr1 ; $cr2 ; }
is not what it seems. Since prototypes, signatures
and signatures with :prototype(&&)
may not be giving you what think you're getting, this might be good enough:
sub doublethecode { eval { shift }; eval{ shift } } ;
doublethecode &{ print "perl" }, &{ print "6" }
output:
perl6
To make sure perl doesn't think {}
is a hash, the &
is necessary. But actually ... what is wrong with using anonymous subroutines sub { }
here?
sub { ... }
is, only you don't type thesub
keyword – Larvaexample2 sub { ... }, sub { ...};
I realise that, I just want to do without thesub
keyword or variables. I'm guessing this can't be done. – Nanettesub try(&@){ ...do stuff with two code refs... } sub catch(&){$_[0]}
, usable liketry { ... } catch { ... };
(don't forget the semicolon). Having the second sub's name there to label what that block of code does is IMO an advantage over justfoo { ... } { ... }
(which doesn't work). If you can see @WumpusQ.Wumbley 's deleted answer, this is exactly what he suggests. Err, as is true of @Borodin's answer, which I somehow totally missed. – AgoneTry::Tiny
? That is as it should be: there is no place for subroutine prototypes in any mainstream Perl code. – Tierney(&&)
, but you can only pass a block of code without thesub
keyword once, and I wondered if I was missing something, the documentation wasn't helpful. – Nanette