在我的 Moose 对象中需要管理文件权限属性。很高兴接受任何变体,例如:
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
所以,寻找一些东西
has 'perm' => (is => 'rw', isa => Perm, coerce => 1, default => sub { oct('0444') });
例如想要将权限存储为一个数字(在文件操作中可用的内容)。
但不知道如何创建
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);
上面的打印:
dec:333 oct:515
dec:383 oct:577
dec:219 oct:333
Attribute (perm) does not pass the type constraint because: octal perm out of range at ....
例如。以八进制形式输入的烫发(并检测到超出范围),但来自字符串
最佳答案
尝试这样的事情:
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 是留给读者的练习。关于perl - Moose 强制转换为文件权限八进制值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30851147/