3

我有一个自定义的 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($_) };

我想在字典中使用该 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 继承并运行在成员类型上定义的类型强制的自定义类型?

4

1 回答 1

2

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 );

tester.pl:

#!perl
use MyObj;
my $obj = MyObj->new( whatsis => { name => 'Something', date => '2016-01-01' } );
use Data::Dumper; print Dumper $obj;
于 2017-08-24T06:01:20.197 回答