nohat has asked for the wisdom of the Perl Monks concerning the following question:

I have a subroutine that returns subroutines that I use as callbacks for TK. Is it possible for the anonymous subroutines returned by my make_read_file_proc() subroutine to be recursive? That is, is it possible for anonymous subroutines to call themselves? If so, how?

Here is my function so far: (there might be errors here, I have only proved it correct (er, written it), not tried it)

sub make_read_file_proc { my $fh = shift; return sub { if eof($fh) { $root->fileevent($fh, "readable", undef); $fh->close; $nextfile = get_next_file(); # do stuff to start processing next file # this is where I want to call myself recursively, # if I could } if (<fh>) { #do stuff to process output from forked children here #right now, just print print; } else { print "error\n"; $root->fileevent($fh, "readable", undef); undef($fh); } } }
-- nohat

Replies are listed 'Best First'.
Re: Recursive anonymous subroutines
by BrowserUk (Patriarch) on Oct 07, 2003 at 23:35 UTC

    See Re: Anonymous coderefs.


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail

Re: Recursive anonymous subroutines
by pg (Canon) on Oct 08, 2003 at 01:04 UTC

    So I assume what you did is, to have a sub, which returns a sub routine, base on some sort of condition, either by using switch statement, or whole bunch of elsif.

    Hm... This sub itself would be a giant, and I don't see this as a good style.

    What you really should do, is to have all those subs well defined, give each of them a name THAT HELPS PEOPLE TO UNDERSTAND THEIR FUNCTONALITY. You can use ref to those subs to implement what you stated.

      Er, no, if you look at the code you will see the only difference between the different anonymous subs is which filehandle they read from. It is not possible to pass in the filehandle because they are used as callbacks. And the filehandles are all just members of an array, so there is no point in making separate subs for each, and besides I don't know how many there will be so it's not really possible anyway. -- Nohat
Re: Recursive anonymous subroutines
by nohat (Initiate) on Sep 21, 2006 at 07:59 UTC
    In case anyone stumbles on this old discussion, despite the two essentially useless responses from others, the answer is YES, it is possible to implement recursive anonymous functions in Perl, using the Y combinator, just as you would in a more purely functional language, like Scheme. A good discussion of this is here: http://use.perl.org/~Aristotle/journal/30896