Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Re^3: recursive anonymous subroutines

by snoopy (Deacon)
on Apr 10, 2006 at 04:28 UTC ( #542206=note: print w/replies, xml ) Need Help??

in reply to Re^2: recursive anonymous subroutines
in thread recursive anonymous subroutines

It's a recursive, i.e. leaking, reference.

Hmm... probably safer to keep the reference on the call stack, thus releasing it on exit.

For example, adopting the convention that the reference is always passed as the first parameter:

my @factorials = map { $_[0] ||= sub { my $factor = pop; return $factor > 1 ? &{$_[0]}($_[0],$factor-1) * $factor : 1; }; &{$_[0]}($_[0],$_)} (3,5,7,9);
sub make_call { goto $_[0]; } my @factorials = map { make_call (sub { my $factor = $_[1]; return $factor > 1 ? make_call($_[0], $factor-1) * $factor : 1; }, $_); } (3,5,7,9);

Replies are listed 'Best First'.
Re^4: recursive anonymous subroutines
by Daryn (Sexton) on Apr 10, 2006 at 12:05 UTC
    Very nice! I believe your make_call version will shortly become a new idiom in my code. Many thanks!
Re^4: recursive anonymous subroutines
by runrig (Abbot) on Apr 11, 2006 at 23:26 UTC
    Just thought I'd point out that this is an interesting reinvention of a previous post (though with one less level into the call stack due to the goto). Compare:
    # Your's: sub make_call { goto $_[0] } # Anonymonk's(slightly rearranged): sub Y { $_[0]->(@_) }
    Update: Well, it's more the same if you change your call to:
    make_call (sub { my $factor = $_[1]; return $factor > 1 ? $_[0]->($_[0], $factor-1) * $factor : 1; }, $_);

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://542206]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2017-02-22 05:08 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (324 votes). Check out past polls.