in reply to how can i hold temporary values in a recursive function

Several ways:

  1. Simple closure:
    { my %state; sub recursive { my $arg = shift; ... if( ( $arg = $state{ $arg } ) == ... ) { return recursive( $arg ); else { return 0 } } }
  2. Closure via helper function:
    sub rec_helper { my %state; my $recursive; $recursive = sub { my( $arg ) = shift; ... if( ( $arg = $state{ $arg ) ) == ... ) { return $recursive->( $arg ); } else { return 0; } }; }
  3. State passed through args (often via helper function ):
    sub recursive { my( $state, $arg ) = @_; ... if( ( $arg = $state->{ $arg } ) == ... ) { return recursive( $state, $arg ); } else { return 0; } } sub rec_helper{ my $arg = shift; my %state; return recursive( \%state, $arg ); }

And many variations on those themes.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
RIP an inspiration; A true Folk's Guy

Replies are listed 'Best First'.
Re^2: how can i hold temporary values in a recursive function
by ikegami (Patriarch) on Apr 18, 2010 at 21:04 UTC
    #2 leaks memory every time you call rec_helper. The sub you create references $recursive which references the sub, so you have a memory cycle. The simplest solution is to avoid using a lexical to hold the reference to the sub. It even simplifies the code a little.
    sub rec_helper { my %state; local *recursive = sub { my( $arg ) = shift; ... if( ( $arg = $state{ $arg ) ) == ... ) { return recursive( $arg ); } else { return 0; } }; }