gpt4 book ai didi

perl - 定义和转换 Moose 属性类型的正确方法

转载 作者:行者123 更新时间:2023-12-05 00:45:19 24 4
gpt4 key购买 nike

有:

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,所以,$o1->path $o2->path 应该返回 blessed Path::Class::Dir

当我尝试将定义扩展到下一个时:

has 'path' => (
is => 'ro',
isa => 'Path::Class::Dir|Str', #allowing both attr types
required => 1,
);

它不起作用,仍然需要在 package MyPath< 内部自动“有点”将 Str 转换为 Path::Class::Dir/...

有人可以给我一些提示吗?

编辑:根据 Oesor 的提示,我发现我需要这样的东西:

coerce Directory,
from Str, via { Path::Class::Dir->new($_) };

has 'path' => (
is => 'ro',
isa => 'Directory',
required => 1,
);

但还是不知道如何正确使用它...

请提供更多提示?

最佳答案

您正在寻找类型强制。

use Moose;
use Moose::Util::TypeConstraints;
use Path::Class::Dir;

subtype 'Path::Class::Dir',
as 'Object',
where { $_->isa('Path::Class::Dir') };

coerce 'Path::Class::Dir',
from 'Str',
via { Path::Class::Dir->new($_) };

has 'path' => (
is => 'ro',
isa => 'Path::Class::Dir',
required => 1,
coerce => 1,
);

关于perl - 定义和转换 Moose 属性类型的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19623088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com