在我的Moose对象中需要管理file-permission属性。很高兴接受任何变体,例如:
AddWithValue("@taj", value)
还会验证访问者设置的值,例如:
my $obj = My::Obj->new(); # should assign default 0444
my $obj = My::Obj->new(perm => '1666'); #as string
my $obj = My::Obj->new(perm => 0555); #as octal
所以,寻找一些东西
$obj->perm('0666');
#etc
e.g。希望将权限存储为数字(文件操作中可用的内容)。
但不知道如何创建has 'perm' => (is => 'rw', isa => Perm, coerce => 1, default => sub { oct('0444') });
类型,
e.g。尝试了像
这样的东西Perm
但上面将其验证为subtype 'Perm',
as 'Str', #but i want store a number
where { $_ =~ /\A[01246]?[0-7]{3}\z/ }; #but i know the validation for strings only
并且我想存储Str
值,所以我迷路了。;(
有人可以帮忙吗?
还在与此作斗争。
octal
以上版画:
package Some;
use 5.018;
use warnings;
use namespace::sweep;
use Moose;
use Moose::Util::TypeConstraints;
subtype 'Perm', as 'Int', where { $_ >= 0 and $_ <= 06777 }, message { 'octal perm out of range' };
subtype 'PermStr', as 'Str', where { $_ =~ /\A[01246]?[0-7]{3}\z/ }, message { 'bad string-perm' };
coerce 'Perm', from 'PermStr', via { oct("$_") };
has 'perm' => ( is => 'rw', isa => 'Perm', coerce => 1, default => 0444, );
no Moose::Util::TypeConstraints;
package main;
my($p,$q);
$p = '0333' ; $q = Some->new(perm => $p); printf("dec:%d oct:%o\n", $q->perm, $q->perm);
$p = '0383' ; $q = Some->new(perm => $p); printf("dec:%d oct:%o\n", $q->perm, $q->perm);
$p = 0333 ; $q = Some->new(perm => $p); printf("dec:%d oct:%o\n", $q->perm, $q->perm);
$p = 033333 ; $q = Some->new(perm => $p); printf("dec:%d oct:%o\n", $q->perm, $q->perm);
E.g。 perm以八进制形式输入(并检测超出范围),但是来自字符串
答案 0 :(得分:2)
尝试这样的事情:
subtype 'Perm',
as 'Int',
where { $_ >= 0 and $_ <= 06777 };
subtype 'PermStr',
as 'Str',
where { $_ =~ /\A[01246]?[0-7]{3}\z/ };
coerce 'Perm',
from 'PermStr',
via { oct($_) };
请勿忘记使用coerce => 1
声明您的属性。
注意:我为where
提供的Perm
条款比您为PermStr
提供的条款限制性更小。将其更改为不允许03000-03777和05000-05777是留给读者的练习。