Moose Attribute - create your own subtype



examples/Moose/person04/script/person.pl
use strict;
use warnings;
use v5.10;

use Person;
use DateTime;

my $student = Person->new( name => 'Foo' );

$student->sex('m');
say $student->sex;

$student->sex('male');

examples/Moose/person04/lib/Person.pm
package Person;
use Moose;
use Moose::Util::TypeConstraints;

subtype 'Person::Type::Sex'
  => as 'Str'
  => where { $_ eq 'f' or $_ eq 'm' }
  => message { "($_) is not a valid sex. Valid values are 'f' and 'm'." };

has 'name'     => (is => 'rw');
has 'birthday' => (isa => 'DateTime', is => 'rw');
has 'sex'      => (isa => 'Person::Type::Sex', is => 'rw');

1;

examples/Moose/person04/err.txt
Attribute (sex) does not pass the type constraint because:
  (male) is not a valid sex.
  Valid values are 'f' and 'm'. at script\person.pl line 13