in reply to recursive anonymous subroutines
What's wrong storing a reference to an anonymous inner sub in an anonymous outer closure?
Eg to create an recursive factorial subroutine:
This is localised and lends itself to functional usage, eg:#!/usr/bin/perl use strict; my $sub = do { my $this_sub; $this_sub = sub { my $factor = int(shift); return $factor > 1 ? &$this_sub($factor-1) * $factor : 1; }; }; print "factorial of 7 is ".&$sub(7)."\n";
Update: see below for revised solution.my @factorials = map {&{ my $this_sub; $this_sub = sub { my $factor = int(shift); return $factor > 1 ? &$this_sub($factor-1) * $factor : 1; }}($_)} (3,5,7,9); print "factorials: @factorials\n";
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: recursive anonymous subroutines
by Anonymous Monk on Apr 08, 2006 at 21:51 UTC | |
by snoopy (Curate) on Apr 10, 2006 at 04:28 UTC | |
by Daryn (Sexton) on Apr 10, 2006 at 12:05 UTC | |
by runrig (Abbot) on Apr 11, 2006 at 23:26 UTC | |
by snoopy (Curate) on Apr 18, 2006 at 00:58 UTC |
In Section
Seekers of Perl Wisdom