Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Moose Attribute - coercion

  • coercion
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

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;

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