我试图将一个例程传递给 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/