ste*_*nmm 2 perl perl-module pass-by-reference
我试图将例程传递给Perl模块中的另一个子例程.但是当我传递子引用时,传入的ref不再具有对象数据.也许它不可能这样做.我有一个问题的行是下面的"除非"行:
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
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以更改"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";
}
}
Run Code Online (Sandbox Code Playgroud)
更新:
另一个选项是,因为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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2899 次 |
| 最近记录: |