On 12 December 2010 21:26, Father Chrysostomos <perlbug-followup@perl.org> wrote: > # New Ticket Created by Father Chrysostomos > # Please include the string: [perl #80628] > # in the subject line of all future correspondence about this issue. > # <URL: http://rt.perl.org/rt3/Ticket/Display.html?id=80628 > > > > This patch adds a __SUB__ keyword that returns the current subroutine, or undef for the main program, a special block, or an eval. > > If there are no objections, I will add docs and push this shortly before 5.13.8. > > I first thought of adding this to make recursive lexicals subs easier to write (whenever they are added): > > my sub foo { __SUB__->() } > > my sub foo; # the alternative > my sub foo { foo() } > > > The really neat thing, which I realised only after writing it, is that it allows for recursive closures to be written much more simply: > > sub make_recursive_function { > my $arg = shift; > sub { > print "$_[0]\n"; > __SUB__->($_[0] + 1) if $_[0] < $arg; > } > } > > as opposed to: > > use Scalar::Util; > sub make_recursive_function { > my $arg = shift; > my $sub; > my $life_raft = $sub = sub { > print "$_[0]\n"; > &$sub($_[0] + 1) if $_[0] < $arg; > } > Scalar::Util::weaken($sub); > $sub; > } And this demonstrates why the patch would be useful. Even FC got the recipe wrong. :-) It should return $life_raft, not $sub, otherwise $sub will be a "dead weakref", and the sub freed by the time this code exits. cheers, Yves -- perl -Mre=debug -e "/just|another|perl|hacker/"Thread Previous | Thread Next