我正在尝试将对属性的编写器方法的引用传递给另一个类方法。自执行 print 语句以来,显然调用了 setter 方法。但是,会导致以下错误:
Attribute (dir) is required, so cannot be set to undef at Test.pm line 51
Test::_validateDir('Test=HASH(0x2270be0)', 'CODE(0x22a90f8)') called at test.pm line 37
Test::BUILD('test_moose=HASH(0x2270be0)', 'HASH(0x1879728)') called at generated method (unknown origin) line 50
Test:new('Test', dir=>'my_bin') called at ./test_moose.pl line 26
是否有原因无法引用生成的 writer 方法,或者在 Moose 中有不同或更好的方法来执行此操作吗?
这是代码:
package Test;
use Moose;
use File::Spec;
has 'dir' => (is => 'ro', isa => 'Str', required => 1, writer '_set_dir',);
sub BUILD {
my ($self, $hr) = @_;
$self->_validateDir(\&_set_dir);
}
sub _validate_dir {
my ($self, $setter) = @_;
my $dir = File::Spec->rel2abs($self->dir, '/home/me');
if (! -e $dir) {
print "creating directory\n";
#create directory
}
&$setter($dir);
}