这是一个使用trigger function的示例:
package Foo;
use Moose;
has 'option_index' => (
isa => 'Int',
is => 'rw',
default => 0,
);
my $options = [qw(one two three)];
has 'option' => (
is => 'rw',
isa => 'Str',
trigger => \&_set_option_trigger,
);
sub _set_option_trigger {
my ( $self, $new_value, $old_value ) = @_;
for my $idx (0..$#$options) {
if ($options->[$idx] eq $new_value) {
$self->option_index($idx);
return;
}
}
die "Unknown option '$new_value'";
}
no Moose;
__PACKAGE__->meta->make_immutable;
package main;
use strict;
use warnings;
use feature qw(say);
my $foo = Foo->new();
$foo->option('three');
say "Option is: ", $foo->option;
say "Option index is : ", $foo->option_index;
$foo->option('four');
输出:
Option is: three
Option index is : 2
Unknown option 'four' at ./p.pl line 30.
编辑:
要让option 属性具有由option_index 属性确定的默认值,您可以尝试添加lazy 和default 子,如下所示:
has 'option' => (
is => 'rw',
isa => 'Str',
lazy => 1,
default => sub { my $self = shift; $options->[$self->option_index] },
trigger => \&_set_option_trigger,
);