如何在另一个模块的函数调用中传递对模块函数的引用作为参数?
我尝试了以下(简单示例):
这是具有函数(process_staff)的模块,该函数将函数引用(is_ok)作为参数。
#!/usr/bin/perl
use strict;
use warnings;
package Objs::Processing;
sub new {
my ($class) = @_;
bless {} ;
}
sub process_staff {
my ($employee, $func) = @_;
if($func->is_ok($employee)) {
print "Is ok to process\n";
}
else {
print "Not ok to process\n";
}
}
1;
这是实现传递函数的模块(is_ok)
#!usr/bin/perl
use strict;
use warnings;
package Objs::Employee;
my $started;
sub new {
my ($class) = @_;
my $cur_time = localtime;
my $self = {
started => $cur_time,
};
print "Time: $cur_time \n";
bless $self;
}
sub get_started {
my ($class) = @_;
return $class->{started};
}
sub set_started {
my ($class, $value) = @_;
$class->{started} = $value;
}
sub is_ok {
my ($emp) = @_;
print "In is ok I received:\n";
use Data::Dumper;
print Dumper($emp);
return 1;
}
这是我运行的测试脚本:
#!/usr/bin/perl
use strict;
use warnings;
use Objs::Manager;
use Objs::Processing;
my $emp = Objs::Manager->new('John Smith');
use Data::Dumper;
print Dumper($emp);
my $processor = Objs::Processing->new();
$processor->process_staff(\&$emp->is_ok); #error is here
我得到一个:
Not a CODE reference at testScript.pl line 14.
我也试过: $processor->process_staff(\&$emp->is_ok());
但还是不行。
我在这里做错了什么