在以下代码中,我尝试为参数化角色中的属性定义触发器。
#!/usr/bin/env perl
package WordSizeRoleParameterized;
use MooseX::Role::Parameterized;
# a parameterized role with a trigger for an attribute
# does not work
role {
has 'word' => ( is => 'rw', trigger => \&_trigger_word_size,);
has 'word_size' => ( is => 'ro', writer => '_set_word_size', );
method '_trigger_word_size' => sub {
my $self = shift;
my $size;
if ( $self->word ) { $size = split //, $self->word; }
else { $size = 0; }
print "WordsizeRoleParameterized::_trigger_word_size() called : size = $size \n";
$self->_set_word_size($size);
};
};
1;
package WordSizeRole;
use Moose::Role;
# a plain role with a trigger for an attribute
# works as expected
has 'word' => ( is => 'rw', trigger => \&_trigger_word_size,);
has 'word_size' => ( is => 'ro', writer => '_set_word_size', );
sub _trigger_word_size {
my $self = shift;
my $size;
if ( $self->word ) { $size = split //, $self->word;}
else { $size = 0;}
$self->_set_word_size($size);
}
1;
package ClassWordSizeParameterized;
use Moose;
with 'WordSizeRoleParameterized';
1;
package ClassWordSize;
use Moose;
with 'WordSizeRole';
1;
#------------
package main;
#------------
use strict;
use warnings;
# no error
my $wordy = ClassWordSize->new({'word' => 'goodie'});
print "word : '", $wordy->word, "', size: ", $wordy->word_size, "\n";
# but using the paramaeterized role ...
my $wordy_parameterized = ClassWordSizeParameterized->new();
# will cause an error if calling $wordy_parameterized->word('Superdubadubaduuuh'));
#
# Undefined subroutine &WordSizeRoleParameterized::_trigger_word_size called at accessor
# ClassWordSizeParameterized::word (defined at roleTrigger.pl line 8) line 7.
$wordy_parameterized->word('Superdubadubaduuuh');
print "word : '", $wordy_parameterized->word, "', size: ", $wordy_parameterized->word_size, "\n";
调用 $wordy_parameterized->word('Superdubadubaduuuh'),它应该触发触发例程导致错误:Undefined subroutine &WordSizeRoleParameterized::_trigger_word_size called
有趣的是,WordSizeRoleParameterized::_trigger_word_size 方法存在(您可以调用 $wordy_parameterized->_trigger_word_size();),但它不会作为属性的触发例程触发。MooseX::Role::Parameterized 的文档没有说明任何内容。
MooseX::Role::Parameterized 的某些实现细节是否不允许或完全不可能?