in reply to Iterative anonymous subroutines

What you describe is recursive, not iterative. It won't work because as you noted $anon is not defined until the end of the statement, and as far as I know a subroutine can not be a closure on itself. Perhaps if you explained why you're attempting such an odd thing, we could provide a better way to do it.

Replies are listed 'Best First'.
Re^2: Iterative anonymous subroutines
by demerphq (Chancellor) on Dec 13, 2005 at 17:31 UTC

    Closures that enclose themself represent a reference cycle which is a.k.a. a memory leak. If you need a self referencing sub you should localize a glob to do it. Ie:

    local *recursive=sub { ... recursive(...); };

    This keeps the self references "soft" and means that when it goes out of scope the sub will be freed. Doing it via lexicals is not correct

    my $recursive; $recursive=sub{ ... $recursive->(...); };

    as it will leak. (Meaning the sub referenced by $recursive will not be freed until global destruction.)

    ---
    $world=~s/war/peace/g

      See also Sub::Recursive which handles all that for you in a clean way.
      use Sub::Recursive; my $recursive = recursive { ... $REC->(...) ... };