in reply to private recursive subroutines

You can get around that by simply declaring $func as an undefined lexical and then re-defining it as a subroutine. Since the recursive call doesn't get executed until the sub is called for the first time, by that time, $func will contain the code reference. For example,

my $fac; $fac = sub { my ( $n ) = @_; return 1 if $n == 1; return $n * $fac->( $n - 1 ); }; print $fac->( 5 );

Yes, I know factorials are a bad example for recursion; it's just the first thing that came to mind. :)

Replies are listed 'Best First'.
Re^2: private recursive subroutines
by blokhead (Monsignor) on May 10, 2007 at 16:36 UTC
    This approach introduces a cyclic reference with $fac.
    use Devel::Cycle; my $fac; $fac = sub { my ( $n ) = @_; return 1 if $n == 1; return $n * $fac->( $n - 1 ); }; find_cycle($fac); __END__ Cycle (1): $A variable $fac => \&A

    blokhead

      I can't say I understand much how the cycle gets introduced. Anyway, does undef $fac after the usage solve it?
Re^2: private recursive subroutines
by Sixtease (Friar) on May 10, 2007 at 15:58 UTC

    Wow this is cool and so much better than my solution! Thanks, I'll use it right away.

Re^2: private recursive subroutines
by naikonta (Curate) on May 10, 2007 at 15:51 UTC
    The F is probably the most popular, followed by fibonacci. Both are mostly demonstrated at the normal sub level. There should be some specific merit(s) to have this recursive closure. But I will keep this in mind, though, and perhaps use it someday.

    Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!