有:
package MyPath;
use strict;
use warnings;
use Moose;
has 'path' => (
is => 'ro',
isa => 'Path::Class::Dir',
required => 1,
);
1;
但是想用两种方式创建这个对象,比如:
use strict;
use warnings;
use MyPath;
use Path::Class;
my $o1 = MyPath->new(path => dir('/string/path')); #as Path::Class::Dir
my $o2 = MyPath->new(path => '/string/path'); #as string (dies - on attr type)
当使用 'Str' 调用它时 - 想要在 MyPath 包中将其内部转换为 Class::Path::Dir,因此,both:$o1->path
和$o2->path
应该返回祝福Path::Class::Dir
当我尝试将定义扩展到下一个时:
has 'path' => (
is => 'ro',
isa => 'Path::Class::Dir|Str', #allowing both attr types
required => 1,
);
它不起作用,仍然需要“在某种程度上”在内部自动转换Str
为...Path::Class::Dir
package MyPath
有人可以给我一些提示吗?
编辑:根据 Oesor 的提示,我发现比我需要的东西像:
coerce Directory,
from Str, via { Path::Class::Dir->new($_) };
has 'path' => (
is => 'ro',
isa => 'Directory',
required => 1,
);
但是仍然不知道如何正确使用它...
请问还有更多提示吗?