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
and also
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.
use strict;
use warnings;
sub please(&$) {
my ($code1, $code2) = @_;
$code1->();
$code2->();
}
sub also(&) {
$_[0];
}
please { print "aaa\n" } also { print "bbb\n" };
output
aaa
bbb
works for me...
sub example2 {
my $code_ref = shift;
my $code_ref2 = shift;
$code_ref->();
$code_ref2->();
}
example2 ( sub { print "One\n" }, sub { print "Hello\n" });
Just for the purposes of TMTOWTDI here is a method that works in somewhat the way that the OP requested
First, make a source filter
package poop;
use Filter::Util::Call;
sub import {
my ($type) = @_;
my ($ref) = [];
filter_add( bless $ref );
}
sub filter {
my ($self) = @_;
my ($status);
if (( $status = filter_read() ) > 0) {
if(!/sub/ && /example2/) {
s/\{/sub \{/g;
}
}
$status;
}
1;
Second the filter must be used
use poop;
sub example2 {
my $code_ref = shift;
my $code_ref2 = shift;
$code_ref->();
$code_ref2->();
}
example2 ( { print "One\n" }, { print "Hello\n" });
ps. this is horrific and noone would wish to see this actually in production
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With