in reply to Re^3: Reference to an anon sub from within.
in thread Reference to an anon sub from within.
As for the anonymity, it is anonymous in that it doesn't have a global name in any package. OK, so someone somewhere has named a reference to it. But that's what we always mean with an anonymous subroutine.my $sub; $sub = sub { my $num = shift; if (0 == $num) { return 1; } else { return $num * $sub->($num - 1); } }; print $sub->(5), "\n"; print $sub->(6), "\n";
Incidentally in languages that lexically bind calling variables (ie not Perl), and support closures, it is possible to write a recursive function like this using functions of 1 variable without using any declarations or assignments. The trick is kind of complex, here it is (untested, from memory) in JavaScript:
There's no real point to code like this other than so that functional programmers can prove that they're really clever. (OK, I lie, it allows functional programmers to completely do away with side-effects. But I remain convince that proving cleverness is the main goal.)function (builder) { return function (n) { return builder(builder)(n); } }( function (recurse) { return function (n) { if (0 == n) return 1; else return n * recurse(recurse)(n); }; } )( 5 // THIS is the factorial to compute );
|
|---|