In Perl, how can a subroutine get a coderef that points to itself?
Posted
by hillu
on Stack Overflow
See other posts from Stack Overflow
or by hillu
Published on 2010-03-31T15:26:04Z
Indexed on
2010/03/31
15:43 UTC
Read the original article
Hit count: 424
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.
© Stack Overflow or respective owner