On Tue, Mar 28, 2017 at 9:27 PM PYH <p...@vodafonemail.de> wrote:

> Hi,
>
> what's the better way to write a recursion in perl's class?
>
> sub my_recursion {
>      my $self = shift;
>      ....
>      if (...) {
>          $self->my_recursion;
>      }
> }
>
> this one?
>

Define better. In general that is the right form (assuming there is some
side effect to calling my_recursion that will cause the if statement to be
false).  If your function is tail recursive and it has the potential to be
deeply nested, then you can take advantage of a quirk of goto to make it
faster and use less memory:

#!/usr/bin/perl

use strict;
use warnings;

{ package A;
sub new { bless {}, shift }

sub recur {
my ($self, $n) = @_;

return "recur done" if $n <= 0;
return $self->recur($n - 1);
}

sub tail_recur {
my ($self, $n) = @_;

return "tail_recur done" if $n <= 0;
@_ = ($self, $n - 1);
goto &tail_recur;
}
}

my $o = A->new;

print $o->recur(1_000_000), "\n";
print $o->tail_recur(1_000_000), "\n";

NOTE: this only works if the code is tail recursive.  That is, the
recursive function does nothing but return the next call's return value.
It works by replacing the function with itself rather than pushing another
copy of the function on the stack.

Reply via email to