如何将函数传递给构造函数,以便类可以在内部使用它?
测试.pl
use Class;
use Loger;
my $loger = Loger->new();
$loger->log('I have logger now, I can log messages!');
my $class = Class->new(\&{ $loger->log }); # here we pass the function (the method of other class) to contructor of a new Class
$class->do_something(); # class uses loger->log internally to report errors
Class.pm 包类;
sub new {
my $self = {};
$self->{log} = shift; # we got logger->log function, save it for future use
return bless $self;
}
sub do_something {
my $self = shift;
open_file or $self->{log}->('Cant open file'); # we can use gotten logger in class
}
1;