Moose touching octal file resolution
My Moose object needs to manage the file permission attribute. It would be nice to accept any option, for example:
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
also checks the value when set by the accessory, for example:
$obj->perm('0666');
#etc
So, looking for something
has 'perm' => (is => 'rw', isa => Perm, coerce => 1, default => sub { oct('0444') });
eg. want to store the resolution as a number (which can be used in file operations).
but have no idea how to create a type Perm
that
- dies of wrong values
- coerces from a valid string to an octal value
- takes a valid octal value
eg. tried something like
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
But the above is checking it like Str
, and I want to store the value octal
, so I lost ..; (
Can anyone please help?
EDIT
Keep fighting this.
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);
the above prints:
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 ....
eg. perm, entered as octal works (and detects out of range) but from a string
- does not check compliance
- and does not perform octal conversion.
source to share
Try something like this:
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($_) };
Don't forget to declare your attributes with coerce => 1
.
Note. The suggestion where
I gave for Perm
is less restrictive than the one you listed for PermStr
. Changing it to disable 03000 - 03777 and 05000 - 05777 is an exercise left for the reader.
source to share