如何创建一个可以接受多个块的Perl子例程? [英] How can I create a Perl subroutine that accepts more than one block?
问题描述
使用原型,您可以创建一个接受例程作为子参数的子例程:
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" };
我如何做同样的事情,但是要使用多个代码块?我想使用代码块,而不是变量或sub { ... }
.
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 { ... }
.
这不起作用:
sub example2 (&&) {
my $code_ref = shift;
my $code_ref2 = shift;
$code_ref->();
$code_ref2->();
}
example2 { print "One\n" } { print "Hello\n" };
出现此错误:
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不允许您将多个裸块传递给子例程,但是第二个实际参数可能是对子例程的调用,该子例程也占用一个块并仅返回代码引用.
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.
该程序演示.请注意,我选择了please
和also
作为子例程的名称.但是您必须使用既适合自己代码功能又不太可能与即将推出的核心语言扩展冲突的东西.
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" };
输出
aaa
bbb
这篇关于如何创建一个可以接受多个块的Perl子例程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!