Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how can a subroutine get a coderef that points to itself?

Tags:

perl

For learning purposes, I am toying around with the idea of building event-driven programs in Perl and noticed that it might be nice if a subroutine that was registered as an event handler could, on failure, just schedule another call to itself for a later time. So far, I have come up with something like this:

my $cb; my $try = 3; $cb = sub {     my $rc = do_stuff();     if (!$rc && --$try) {         schedule_event($cb, 10); # schedule $cb to be called in 10 seconds     } else {         do_other_stuff;     } }; schedule_event($cb, 0); # schedule initial call to $cb to be performed ASAP 

Is there a way that code inside the sub can access the coderef to that sub so I could do without using an extra variable? I'd like to schedule the initial call like this.

schedule_event( sub { ... }, 0); 

I first thought of using caller(0)[3], but this only gives me a function name, (__ANON__ if there's no name), not a code reference that has a pad attached to it.

like image 401
hillu Avatar asked Mar 31 '10 15:03

hillu


1 Answers

__SUB__ has been added in 5.16, providing this usability.

like image 57
Oesor Avatar answered Sep 17 '22 16:09

Oesor