【发布时间】:2015-08-17 19:20:41
【问题描述】:
#!/usr/bin/perl
use strict;
use warnings;
use List::MoreUtils 'uniq';
my %functiontable =();
$functiontable{foo} = \&foo;
sub iterate {
my ($function, $iterations, $argument) = @_;
return $argument unless 0 < $iterations;
return $argument unless $function = $functiontable{$function};
my @functioned = $function->($argument);
my @refunctioned = ();
for my $i (0 .. @functioned - 1) {
push @refunctioned, iterate ($function, ($iterations - 1), $functioned[$i]);
}
return uniq @refunctioned;
}
sub foo {
my ($argument) = @_;
my @list = ($argument, $argument.'.', $argument.',');
return @list;
}
my @results = iterate 'foo', 2, 'the';
print "@results";
这将打印the the. the,,即它不会迭代(递归)。我希望它打印the the. the, the.. the., the,. the,,。
(我使用 Smart::Comments 来检查它是否第二次输入iterate,它确实输入了,但它似乎并没有完成函数中的所有操作。)
我不知道为什么。有人可以帮我找出原因或提出解决方案吗?
【问题讨论】:
-
您将变量
$function从名称修改为子例程引用,然后将引用传递给迭代方法。您可能想再次传递该名称。 -
@Miller,非常感谢。
-
共有三个答案,每个答案都是正确的 AFAICT,每个答案都更强烈地触及到其他人掩盖的一点(Hunter McMillen's 直接使用 ref 作为参数,Borodin's关于究竟是什么导致我的版本失败,Schwern's 关于智能变量的使用)。我不知道该接受哪一个:所有人都非常有帮助。
-
@JQKP
perl -wle '@choices = qw(Schwern Borodin Hunter); print $choices[rand @choices]'
标签: function recursion subroutine perl