gpt4 book ai didi

perl - 在 Type::Tiny 自定义约束中运行强制转换?

转载 作者:行者123 更新时间:2023-12-05 01:34:27 24 4
gpt4 key购买 nike

我有一个自定义 DateTime 类型,它定义了从字符串到 DateTime 的强制转换,如下所示:

package Library;
use Type::Library -base, -declare => qw(DateTime);
use DateTime::Format::ISO8601;

class_type DateTime, { class => 'DateTime' };

coerce DateTime, from Str, via { DateTime::Format::ISO8601->parse_datetime($_) };

我想在 Dict 中使用 DateTime 类型,如下所示:

package MyObj;
use Moo;
$constraint = declare MyType, as Dict[ name => Str, date => DateTime ];

has 'whatsis' => ( is => 'ro', isa => $constraint );

然后将其命名为:

use MyObj;
my $obj = MyObj->new( whatsis => { name => 'Something', date => '2016-01-01' } );

我试过将 coerce => 1 添加到 whatsis 的声明中,但效果不佳。

如何创建继承自 Dict 的自定义类型并运行在成员类型上定义的类型强制转换?

最佳答案

https://metacpan.org/pod/distribution/Type-Tiny/lib/Type/Tiny/Manual/Coercions.pod 的帮助下

图书馆.pm:

package Library;
use Type::Library -base, -declare => qw(Datetime);
use Type::Utils -all;
use Types::Standard -all;
use DateTime::Format::ISO8601;

class_type Datetime, { class => 'DateTime' };
coerce Datetime,
from Str, via { DateTime::Format::ISO8601->parse_datetime($_) };

declare 'MyType', as Dict[ name => Str, date => Datetime ], coercion => 1;

MyObj.pm:

package MyObj;
use Moo;
use Library -all;

has 'whatsis' => ( is => 'ro', isa => MyType, coerce => 1 );

测试器.pl:

#!perl
use MyObj;
my $obj = MyObj->new( whatsis => { name => 'Something', date => '2016-01-01' } );
use Data::Dumper; print Dumper $obj;

关于perl - 在 Type::Tiny 自定义约束中运行强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36228739/

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