我尝试将Perl闭包转换为Moo访问器,如下面的代码所示。不幸的是,代码与Moose一起使用,但是在Moo中抛出异常。
请帮我写一个带有Perl闭包定义的读写访问器的Moo代码(不是默认的访问器,只读取和存储一个简单的值,但读取和写入的访问器应该调用我的闭包)。
#!/usr/bin/perl
package X;
use Moo;
my $BusinessClass = "X";
my $Key = 'zz';
no strict 'refs';
*{"${BusinessClass}::access_$Key"} = sub { "Modified $Key" };
has $Key => ( is => 'rw',
required => 0,
accessor => { $Key => \&{"${BusinessClass}::access_$Key"} },
# predicate => { "has_$Key",\&{"${BusinessClass}::access2_$Key"} },
);
my $obj = X->new;
print $obj->zz, "\n";
答案 0 :(得分:1)
Moo has
似乎没有accessor
选项。
#!/usr/bin/perl
package X;
use Moo;
use feature qw( say );
for my $attr_name (qw( zz )) {
eval(<<'__EOS__' =~ s/ATTR_NAME/$attr_name/gr) or die($@);
sub ATTR_NAME {
my $self = shift;
@_ ? $self->_set_ATTR_NAME($_[0]) : $self->_get_ATTR_NAME()
}
1; # No exception
__EOS__
has $attr_name => (
is => 'rw',
required => 0,
reader => '_get_'.$attr_name,
writer => '_set_'.$attr_name,
);
}
my $obj = X->new;
$obj->zz("abc");
say $obj->zz;
未测试。