Rewriting a recursive function in perl so that it can be used in a list context

Consider the binary tree developed by Moose :: Cookbook :: Basics :: Recipe3

To get all the nodes in the preorder , I could add the following routine to the BinaryTree package

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

The subitem should be used as follows:

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

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

How can I change the routine to use the syntax as shown below:

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

to be able to do things like

for ($btree->pre_order()) { #bla bla } 

later.

Does that make sense, or am I pedantic?

+3
source share
2 answers

What about:

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

You can simply change the caller:

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

Or just change the code like this:

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

; , (TM):

for ( $self->pre_order() ) {
0

All Articles