gpt4 book ai didi

perl - 如何将函数传递给构造函数

转载 作者:行者123 更新时间:2023-12-01 10:59:23 25 4
gpt4 key购买 nike

如何将函数传递给构造函数,以便类可以在内部使用它?

测试.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;

最佳答案

您正在尝试传递方法,而不是函数(或子函数)。单独调用它是行不通的。如果你想要一个对象的方法,传递对象并调用对象上的方法。

my $loger = Loger->new();
$loger->log('I have logger now, I can log messages!');

my $class = Class->new(logger => $loger); # pass the Loger object

Class.pm 中:

package Class;

sub new
{
my ($class, %args) = @_;
my $self = {};
$self->{log} = $args{'logger'}; # store it inside your Class object
return bless $self;
}

sub do_something
{
my $self = shift;
open_file or $self->{log}->log->('Cant open file'); # call its log-method
}

关于perl - 如何将函数传递给构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12583138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com