Help passing reference to class subroutine in Perl.
Posted
by
stephenmm
on Stack Overflow
See other posts from Stack Overflow
or by stephenmm
Published on 2011-03-09T23:53:50Z
Indexed on
2011/03/10
0:10 UTC
Read the original article
Hit count: 340
I am trying to pass a routine to another subroutine within a Perl module. But when I pass the sub reference the passed in ref no longer has the object data. Maybe its not possible to do it this way. The line I have a question about is the "unless" lines below:
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
}
I know that I could change the "get_flag_end" routine to take the value as an argument to the subroutine but what if there was a bunch of stuff done in "get_flag_end" and I needed more members from the object. I simplified the code a bit to make it a little easier to follow.
© Stack Overflow or respective owner