That's the idea, though there is no reason to make the anonymous factorial subroutine (it doesn't factor, it computes factorial) only work properly if you call it just once. See the following:
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";
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.

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:

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 );
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.)

In reply to Re^4: Reference to an anon sub from within. by tilly
in thread Reference to an anon sub from within. by Dedalus

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.