gpt4 book ai didi

perl - 对 Moose 属性应用特定检查(除了 Moose 类型)

转载 作者:行者123 更新时间:2023-12-04 17:40:11 25 4
gpt4 key购买 nike

Moose types很棒,但有时您需要更具体。这些数据类型规则你们都知道:那个参数只能是'A' , 'B''C' ,或者只是一个货币符号,或者必须符合一些正则表达式。

看看下面的例子,它有两个受约束的属性,一个必须是 'm''f' ,另一个必须是有效的 ISO 日期。 Moose 中指定这些约束的最佳方式是什么?我会想到 SQL CHECK子句,但 AFAICS 没有 check Moose 中的关键字。所以我用了trigger ,但听起来不对。有人有更好的答案吗?

package Person;
use Moose;

has gender => is => 'rw', isa => 'Str', trigger =>
sub { confess 'either m or f' if $_[1] !~ m/^m|f$/ };
has name => is => 'rw', isa => 'Str';
has dateOfBirth => is => 'rw', isa => 'Str', trigger =>
sub { confess 'not an ISO date' if $_[1] !~ m/^\d\d\d\d-\d\d-\d\d$/ };

no Moose;
__PACKAGE__->meta->make_immutable;

package main;
use Test::More;
use Test::Exception;

dies_ok { Person->new( gender => 42 ) } 'gender must be m or f';
dies_ok { Person->new( dateOfBirth => 42 ) } 'must be an ISO date';

done_testing;

这是我最终使用的:
package Blabla::Customer;
use Moose::Util::TypeConstraints;
use Moose;

subtype ISODate => as 'Str' => where { /^\d\d\d\d-\d\d-\d\d$/ };

has id => is => 'rw', isa => 'Str';
has gender => is => 'rw', isa => enum ['m', 'f'];
has firstname => is => 'rw', isa => 'Str';
has dateOfBirth => is => 'rw', isa => 'ISODate';

no Moose;
__PACKAGE__->meta->make_immutable;

这是 Moose 版本 1.19,以防万一。我收到以下错误警告 subtype as => 'Str', where => { ... }我错误引入的语法: Calling subtype() with a simple list of parameters is deprecated .所以我不得不根据精美的手册对其进行一些更改。

最佳答案

只需定义您自己的子类型,然后使用它。

package Person;

use Moose::Util::TypeConstraints;

use namespace::clean;
use Moose;

has gender => (
is => 'rw',
isa => subtype(
as 'Str',
where { /^[mf]$/ }
),
);
has name => (
is => 'rw',
isa => 'Str'
);
has dateOfBirth => (
is => 'rw',
isa => subtype(
as 'Str',
where { /^\d\d\d\d-\d\d-\d\d$/ }
),
);

no Moose;
__PACKAGE__->meta->make_immutable;
1;
package main;
use Test::More;
use Test::Exception;

dies_ok { Person->new( gender => 42 ) } 'gender must be m or f';
dies_ok { Person->new( dateOfBirth => 42 ) } 'must be an ISO date';

done_testing;

或者您可以使用 MooseX::Types模块。
package Person::TypeConstraints;

use MooseX::Types::Moose qw'Str';
use MooseX::Types -declare => [qw'
Gender ISODate
'];

subtype Gender, (
as Str,
where { /^[mf]$/ },
);

subtype ISODate, (
as Str,
where { /^\d\d\d\d-\d\d-\d\d$/ }
);
1;
package Person:

use MooseX::Types::Moose qw'Str';
use Person::TypeConstraints qw'Gender ISODate';

use namespace::clean;
use Moose;

has gender => (
is => 'rw',
isa => Gender,
);
has name => (
is => 'rw',
isa => Str,
);
has dateOfBirth => (
is => 'rw',
isa => ISODate,
);

no Moose;
__PACKAGE__->meta->make_immutable;
1;

关于perl - 对 Moose 属性应用特定检查(除了 Moose 类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5822651/

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