<?xml version="1.0" encoding="windows-1252"?>
<node id="541711" title="recursive anonymous subroutines" created="2006-04-06 15:56:41" updated="2006-04-06 11:56:41">
<type id="115">
perlquestion</type>
<author id="539736">
Daryn</author>
<data>
<field name="doctext">
Greetings gentle monks, 

&lt;/p&gt;is there a magic way to call an anonymous subroutine within its own body without binding it to a coderef ? 

&lt;/p&gt;I'd like to do something like that: 

&lt;code&gt;
(sub {... magic(...) ... )-&gt;(args)
&lt;/code&gt;

where &lt;code&gt;magic&lt;/code&gt; would refer to the anonymous sub being defined. 

&lt;/p&gt;The closest I came so far was 

&lt;code&gt;
use strict;
{
    my $coderef;
    ($coderef = sub { ... $coderef-&gt;(...) ...)-&gt;(args);
}
&lt;/code&gt;

which strikes me as inelegant and potentially leaky. Here is some runnable (if silly) code :

&lt;code&gt;
use strict; 

# direct call of unbound non recursive anonymous subroutine
my $res = (sub{ print @_[0] + @_[1] . "\n\n";})-&gt;(100,1);

# need to bind to a coderef if recursive ?
{
    my $coderef;
    ($coderef = sub {return unless $_[0] &gt; 0; print "$_[0]\n"; $coderef-&gt;($_[0]-1)})-&gt;(4);
}
&lt;/code&gt;

&lt;/p&gt;In real life, I sometimes need to call a recursive function or subroutine to process a tree-like structure. It gets called only once, at a specific point, and should (IMO) not need to be graced with a name or bound to a coderef (much in the spirit of a &lt;code&gt;map {...} @somearray&lt;/code&gt;).

&lt;/p&gt;Any thoughts ? TIA.
</field>
</data>
</node>
