You can also solve this problem using a combination of a fixed point combinator (don't worry it's not as complex as it sounds) and currying.

Basically your problem is that you have a un-nameable subroutine which you want to recurse with. The problem is you are trying to call your subroutine by name, which is not possible since it's name can never be in the proper scope. The other option then is to call-by-value instead. In order to accomplish this, all you need to do is alter your anon-subroutine to take an additional parameter, which is the function you wish to call in the recursion. It might look something like this:

my $anon = sub { my $func = shift; my $count = shift; if ($count--) { print "Iterating\n"; $func->($count); } };
Now when you want to call this sub, you have to pass the sub itself as it's first parameter, and now you have your recursion.

Of course, this is most likely inconvient to have to do this. Fear not! Currying to the rescue! Just do this:

my $counter = sub { $anon->($anon, shift) };
And return $counter instead of $anon, and you have exactly what you are looking for.

Hope this helps :)

-stvn

In reply to Re: Iterative anonymous subroutines by stvn
in thread Iterative anonymous subroutines by Anonymous Monk

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.