You can define a subtype with a type constraint.
The syntactic sugar for working with this is provided by Moose::Util::TypeConstraints.
package My;
use 5.16.0;
use Moose;
use Moose::Util::TypeConstraints; # provides sugar below
subtype 'ExistingDir' => (
as 'Str',
where { -d $_ },
message { 'The directory does not exist' }
);
has 'mydir' => (
is => 'ro',
isa => 'ExistingDir',
required => 1,
);
package main;
my $foo = My->new(mydir => 'perl'); # exists
say $foo->mydir();
my $bar = My->new(mydir => 'perlXXX'); # does not exist, so dies here...
outputs:
>mkdir perl
>perl foo.pl
perl
Attribute (mydir) does not pass the type constraint because: The directory does not exist at ...