我开始将几个 Perl 模块迁移到Moo,但因为 setter/writer 只能有一个参数(不是吗?)而被卡住了。这也适用于强制:
package MyThing:
use Moo;
use Scalar::Util qw(blessed);
use SomeOtherThing;
has foo => (
is => 'rw',
coerce => sub {
return $_[0] if blessed($_[0]) and $_[0]->isa('SomeOtherThing');
return SomeOtherThing->new( @_ ); # does not work, because @_ == 1
},
);
这是一个简单的用例:
package MyApplication;
use MyThing;
$thing = MyThing->new;
$thing->foo( 'some', 'values'); # would like to have this shortcut
$thing->foo; # expected a SomeOtherThing
# must use this ugly form instead
$thing->foo( SomeOtherThing->new('some', 'values') );
有没有一种简单的方法来实现支持多参数设置的访问器?