我可以在 Moose 中使用 isa 和正则表达式作为参数吗?如果不可能,我可以用其他东西实现同样的目标->isa
吗?
好的,有以下类型 Animal::Giraffe
,Animal::Carnivore::Crocodile
我想做,我->isa(/^Animal::/)
可以这样做吗?如果我不能,我可以用什么来达到预期的效果?
这些相关的类型都应该“做”相同的角色,Animal。然后你可以写:
has 'animal' => (
is => 'ro',
does => 'Animal',
required => 1,
);
现在你有了比正则表达式更可靠的东西来确保程序的一致性。
虽然我会使用 Moose::Util::TypeConstraints 的糖,但 Leon Timmermans 的回答与我的建议很接近
use Moose;
use Moose::Util::TypeConstraints;
subtype Animal => as Object => where { blessed $_ =~ /^Animal::/ };
has animal => ( is => 'rw', isa => 'Animal' );
扩展 perigrin 的答案,以便如果该类Animal::*
在其超类中有任何位置,而不仅仅是在其直接类名中(例如 if Helper::Monkey
isa Animal::Monkey
),它将起作用:
use Moose;
use Moose::Util::TypeConstraints;
subtype Animal =>
as Object =>
where { grep /^Animal::/, $_->meta->linearized_isa };
has animal => ( is => 'rw', isa => 'Animal' );
我认为 jrockway 建议使用角色来代替有很多优点,但是如果您想改用这种方式,则不妨涵盖所有基础。
我认为应该这样做。
use Moose;
use Moose::Util::TypeConstraints;
my $animal = Moose::Meta::TypeConstraint->new(
constraint => sub { $_[0] =~ /^Animal::/}
);
has animal => (is => 'rw', isa => $animal);
ETA:我同意 jrockway 的观点:除非你有令人信服的理由,否则你应该只使用继承。