我正在使用Perl中的一些代码,希望我将方法传递给它。但是,我想保留一些关于方法中发生的事情的状态。我知道我可以使用全局变量,但我更喜欢一些更清洁/面向对象的东西。有没有办法使用Moose创建一个仿函数/函数对象?
答案 0 :(得分:5)
你只需要一个关闭。
sub make_closure {
my ($name) = @_;
my @greets = ('Good morning', 'Good afternoon', 'Good evening', 'Good night');
my $next = 0;
return sub { "$greets[ $next++ % @greets ], $name" };
}
my $joe = make_closure("Joe");
my $jane = make_closure("Jane");
say $joe->(); # Good morning, Joe
say $joe->(); # Good afternoon, Joe
say $jane->(); # Good morning, Jane
say $jane->(); # Good afternoon, Jane
say $jane->(); # Good evening, Jane
say $joe->(); # Good evening, Joe
另一种方法是制作一个overloads &{}
。
use Moose;
use overload '&{}' => \&call;
has code => ( is => 'rw' );
has called => ( is => 'rw', default => 0 );
sub call {
my ($self) = @_;
$self->called( $self->called() + 1 );
return $self->code;
}
my $o = __PACKAGE__->new(code => sub { say "called!" });
$o->(); # called!
$o->(); # called!
say $o->called; # 2