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

后端 未结 5 736
情歌与酒
情歌与酒 2020-12-24 07:02

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

相关标签:
5条回答
  • 2020-12-24 07:30

    I think Sub::Current will fix your problem.

    0 讨论(0)
  • 2020-12-24 07:35

    To get a reference to the current subroutine without using an extra variable, you can use a tool from functional programming, the Y-combinator, which basically abstracts away the process of creating the closure. Here is a perlish version:

    use Scalar::Util qw/weaken/;
    
    sub Y (&) {
        my ($code, $self, $return) = shift;
        $return = $self = sub {$code->($self, @_)};
        weaken $self;  # prevent a circular reference that will leak memory
        $return;
    }
    
    schedule_event( Y { my $self = shift; ... }, 0);
    
    0 讨论(0)
  • 2020-12-24 07:40

    __SUB__ has been added in 5.16, providing this usability.

    0 讨论(0)
  • 2020-12-24 07:48

    If you don't change $cb's value again, you can use that. If not, define a scalar to hold that and don't change it ever again. For example:

    my $cb = do {
      my $sub;
      $sub = sub { contents using $sub here }
    }
    
    0 讨论(0)
  • 2020-12-24 07:51

    Using a fixed-point combinator, you can write your $cb function as if the first argument was the function itself:

    sub U {
      my $f = shift;
      sub { $f->($f, @_) }
    }
    
    my $cb = sub {
      my $cb = shift;
      ...
      schedule_event(U($cb), 10);
      ...
    }
    
    schedule_event(U($cb), 0);
    
    0 讨论(0)
提交回复
热议问题