如何在Perl中迭代/解引用子例程引用数组? [英] How do I iterate over/dereference an array of subroutine refs in Perl?
问题描述
我正在尝试弄清如何遍历一系列子例程引用.
I’m trying to figure out how to iterate over an array of subroutine refs.
此语法有什么问题?
use strict;
use warnings;
sub yell { print "Ahh!\n"; }
sub kick { print "Boot!\n"; }
sub scream { print "Eeek!\n"; }
my @routines = (\&yell, \&kick, \&scream);
foreach my $routine_ref (@routines) {
my &routine = &{$routine_ref};
&routine;
}
提前谢谢!
推荐答案
在您的foreach
循环中,以下是语法错误:
In your foreach
loop, the following is a syntax error:
my &routine;
您的变量$routine_ref
已经有对该子例程的引用,因此此时您需要做的就是调用它:
Your variable $routine_ref
already has a reference to the subroutine, so all you need to do at that point is call it:
for my $routine_ref (@routines) {
&{$routine_ref};
}
与Perl一样,实现这一目标的方法不止一种."例如,如果这些子例程中的任何一个都带有参数,则可以像这样在括号内传递它们:
As always with Perl, "There's More Than One Way to Do It." For example, if any of those subroutines took parameters, you could pass them inside parenthesis like this:
for my $routine_ref (@routines) {
$routine_ref->();
}
还请注意,我使用的是for
而不是foreach
,这是 Damian Conway的Perl最佳做法.
Also note that I've used for
instead of foreach
, which is a best pratice put forth by Damian Conway in Perl Best Practices.
这篇关于如何在Perl中迭代/解引用子例程引用数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!