4

肯定是一个非常简单的问题,但我仍在学习并没有找到答案。

需要检查 Moose 对象构造函数提供的(必需的)参数的有效性,例如下一个示例:

use 5.016;
use warnings;

package My {
    use Moose;
    has 'mydir' => (
        is          => 'ro',
        isa         => 'Str',
        required    => 1,
    );
}

use File::Path qw(remove_tree);
package main {
    my @dirs = qw(./d1 ./d2);

    #ensure no one dir exists
    remove_tree($_) for ( @dirs );

    #create the first dir
    mkdir $dirs[0] or die;

    foreach my $dir( @dirs ) {
        my $m = My->new( mydir=>$dir );
        say "$dir ", defined($m) ? "" : "NOT", " ok";
    }
}

问题是:我应该在My包中添加什么以确保在提供的路径存在时才创建My对象?所以某处需要添加测试。mydirif -d ...

如何定义mydir具有有效性检查的属性?

主程序的想要的结果:

./d1 ok
./d2 NOT ok
4

1 回答 1

4

您可以定义具有类型约束的子类型。

Moose::Util::TypeConstraints提供了使用它的语法糖。

package My;
use 5.16.0;

use Moose;
use Moose::Util::TypeConstraints; # provides sugar below

subtype 'ExistingDir' => (
    as 'Str',
    where { -d $_ },
    message { 'The directory does not exist' }
    );

has 'mydir' => (
        is          => 'ro',
        isa         => 'ExistingDir',
        required    => 1,
    );

package main;

my $foo = My->new(mydir => 'perl'); # exists
say $foo->mydir();

my $bar = My->new(mydir => 'perlXXX'); # does not exist, so dies here...

输出:

>mkdir perl
>perl foo.pl

perl
Attribute (mydir) does not pass the type constraint because: The directory does not exist at ...
于 2013-10-20T01:28:47.853 回答