With prototypes, you can create a subroutine that accepts a block of code as its first parameter:
sub example (&) {
my $code_ref = shift;
$code_ref->();
}
example { print "Hello\n" };
How can I do the same thing, but with more than one block of code? I want to use blocks of codes, not variables or sub { ... }
.
This does not work:
sub example2 (&&) {
my $code_ref = shift;
my $code_ref2 = shift;
$code_ref->();
$code_ref2->();
}
example2 { print "One\n" } { print "Hello\n" };
It gives this error:
Not enough arguments for main::example2
I hope you realise that this is just code seasoning, and all you are achieving is a tidier syntax at the expense of clarity?
Perl won't allow you to pass more than one bare block to a subroutine, but the second actual parameter could be a call to a subroutine that also takes a single block and simply returns the code reference.
This program demonstrates. Note that I have chosen
please
andalso
as names for the subroutines. But you must use something that is both appropriate to your own code's functionality and very unlikely to clash with forthcoming extensions to the core language.output