Attribute Type constraint


Checking the value of the attributes.


examples/perloop/person02/script/person.pl
use strict;
use warnings;
use v5.10;

use Person;

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

$student->year(1988);

say $student->year;

$student->year('23 years ago');

examples/perloop/person02/lib/Person.pm
package Person;
use strict;
use warnings;

sub new {
    my ($class, %args) = @_;

    my $self = \%args;

    bless $self, $class;

    return $self;
}

sub name {
    my ($self, $value) = @_;
    if (@_ == 2) {
        $self->{name} = $value;
    }

    return $self->{name};
}

sub year {
    my ($self, $value) = @_;
    if (@_ == 2) {
        die qq{Attribute (year) does not pass the type constraint because: } .
            qq{Validation failed for 'Int' with value "$value"}
            if $value !~ /^\d+$/;
        $self->{year} = $value;
    }

    return $self->{year};
}

1;