在 Perl 中,子程序如何获得指向自身的 coderef? [英] In Perl, how can a subroutine get a coderef that points to itself?

查看:39
本文介绍了在 Perl 中,子程序如何获得指向自身的 coderef?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于学习的目的,我在玩弄构建的想法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

有没有办法让 sub 中的代码可以访问 coderef 到那个sub 这样我就可以不用额外的变量了?我想像这样安排初始通话.

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);

我首先想到使用 caller(0)[3],但这只会给我一个函数名,(__ANON__ 如果没有名字),不是代码引用上面有一个垫子.

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.

推荐答案

__SUB__ 已在 5.16 中添加,提供此可用性.

__SUB__ has been added in 5.16, providing this usability.

这篇关于在 Perl 中,子程序如何获得指向自身的 coderef?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆