在perl中重写递归函数,以便可以在列表上下文中使用它

时间:2011-03-09 18:25:12

标签: perl recursion

考虑在Moose::Cookbook::Basics::Recipe3

中开发的二叉树

要检索所有节点in preorder,我可以将以下子例程添加到BinaryTree包中

sub pre_order {
  my ($self,$aref) = @_;

  push @$aref, $self->node;

  pre_order($self->left,$aref) if $self->has_left;
  pre_order($self->right,$aref) if $self->has_right;
}

sub必须像这样使用:

my $btree = BinaryTree->new;
#add some nodes

#then later...
my @nodes_in_preorder;
$btree->pre_order(\@nodes_in_preorder);

我如何更改子程序才能使用如下语法:

my @nodes_in_preorder = $btree->pre_order();

为了能够做到像

这样的事情
for ($btree->pre_order()) { #bla bla } 

稍后。

这是否有意义,或者我是否迂腐?

2 个答案:

答案 0 :(得分:9)

怎么样:

sub pre_order {
  my $self = shift;
  return ($self->node,
    $self->has_left ? $self->left->pre_order : (),
    $self->has_right ? $self->right->pre_order : ());
}

答案 1 :(得分:0)

您可以更改来电者:

for ( do { my @preorder; $btree->pre_order(\@preorder); @preorder } ) {

或者只是改变代码:

sub pre_order {
    my ($self,$aref) = @_;

    push @$aref, $self->node;

    $self->left->pre_order($aref) if $self->has_left;
    $self->right->pre_order($aref) if $self->has_right;

    return @$aref if wantarray;
}

无需将数组引用传递给外部调用;一个将自动创建,因此您的代码将为Just Work(TM):

for ( $self->pre_order() ) {