perl - 帮助在 Perl 中传递对类子例程的引用

标签 perl pass-by-reference perl-module

我试图将一个例程传递给 Perl 模块中的另一个子例程。但是当我传递子引用时,传入的引用不再具有对象数据。也许不可能这样做。我有疑问的是下面的“除非”行:

sub get_flag_end {
   my $self = shift;
   return ( -e "$self->{file}" );
}

sub wait_for_end {
   my $self = shift;
   my $timeout = shift;
   my $poll_interval = shift;

   # Is it even possible to pass the oject subroutine and retain the objects data?
   #unless ( $self->timeout( $timeout, $poll_interval, $self->get_flag_end ) ) { # does not work
   unless ( $self->timeout( $timeout, $poll_interval, \&get_flag_end ) ) {       # call happens but members are empty
      die "!!!ERROR!!! Timed out while waiting for wait_for_end: timeout=$timeout, poll_interval=$poll_interval \n";
   }
}

sub timeout {
   my $self = shift;
   my $timeout = shift;
   my $poll_interval = shift;
   my $test_condition = shift;
   until ($test_condition->() || $timeout <= 0) {
      $timeout -= $poll_interval;
      sleep $poll_interval;
   }
   return $timeout > 0; # condition was met before timeout
}

我知道我可以更改“get_flag_end”例程以将值作为子例程的参数,但是如果在“get_flag_end”中完成了一堆事情并且我需要该对象的更多成员怎么办。我稍微简化了代码,使其更容易理解。

最佳答案

只需关闭并将其传入:

sub wait_for_end {
   my $self = shift;
   my $timeout = shift;
   my $poll_interval = shift;

   my $callback = sub { $self->get_flag_end() };

   unless ( $self->timeout( $timeout, $poll_interval, $callback ) ) {
      die "!!!ERROR!!! Timed out while waiting for wait_for_end: timeout=$timeout, poll_interval=$poll_interval \n";
   }
}

更新:

另一种选择是,因为timeout是同一个类的方法,所以传入一个方法名。

sub wait_for_end {
   my $self = shift;
   my $timeout = shift;
   my $poll_interval = shift;

   my $callback = sub { $self->get_flag_end() };

   unless ( $self->timeout( $timeout, $poll_interval, 'get_flag_end' ) ) {
      die "!!!ERROR!!! Timed out while waiting for wait_for_end: timeout=$timeout, poll_interval=$poll_interval \n";
   }
}

sub timeout {
  my $self = shift;
  my $timeout = shift;
  my $poll_interval = shift;
  my $method = shift;

  # Do whatever

  # Now call your method.
  $self->$method();

}

关于perl - 帮助在 Perl 中传递对类子例程的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5253833/

相关文章:

c - 我是否正确理解 C 中的按值传递和按引用传递?

c++ - 将引用从 Python 传递给用 swig 包装的 c++ 函数以获得返回值

perl - 如何取消引用 STDIN 文件句柄的副本?

perl - 当安装了两个版本的模块时 Perl 会做什么?

perl - 在perl中,if语句中的-f是什么意思?

multithreading - 如何在 perl 中创建同步方法?

regex - 使用 bash/coreutils 而不是 perl 按函数排序

Java方法参数之谜

perl - 评估和使用问题

perl - 使用 Perl 创建包