Moose Attribute - coercion



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

use Person;
use DateTime;

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

$student->sex('m');        # should be accepted as 'm'
say $student->sex;

$student->sex('female');   # should be accepted as 'f'
say $student->sex;

$student->sex('other');    # should not be accepted

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

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

coerce 'Person::Type::Sex'
    => from 'Str'
    => via { lc substr($_, 0, 1) };

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

1;

examples/Moose/person05/err.txt
Attribute (sex) does not pass the type constraint because: 
   The sex you provided (o) is not valid. Valid values are 'f' and 'm'. 
   at accessor Person::sex (defined at lib/Person.pm line 16) line 8
     Person::sex('Person=HASH(0x24ff918)', 'other')
       called at script/person.pl line 16