4

我试图弄清楚如何迭代一组子程序参考。

这种语法有什么问题?

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;
}

提前致谢!

4

3 回答 3

10

在您的foreach循环中,以下是语法错误:

my &routine;

您的变量$routine_ref已经引用了子例程,所以此时您需要做的就是调用它:

for my $routine_ref (@routines) {
    &{$routine_ref};
}

与 Perl 一样,“有不止一种方法可以做到这一点”。例如,如果这些子例程中的任何一个带有参数,您可以将它们传递到括号中,如下所示:

for my $routine_ref (@routines) {
  $routine_ref->();
}

另请注意,我使用for了而不是,这是Damian Conway 在 Perl Best Practices 中foreach提出的最佳实践。

于 2009-01-17T01:00:05.590 回答
4
foreach my $routine_ref (@routines) {
        $routine_ref->();
}
于 2009-01-17T00:41:20.870 回答
0

试试这个:

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) {
  &$routine_ref ();
}
于 2009-01-17T00:30:27.303 回答