6 Moose::Cookbook::Snack::Types - Snippets of code for using Types and Type Constraints
13 has 'x' => ( isa => 'Int', is => 'ro' );
14 has 'y' => ( isa => 'Int', is => 'rw' );
18 my $point = eval { Point->new( x => 'fifty', y => 'forty' ); };
25 my $xval = 'forty-two';
26 my $xattribute = Point->meta->find_attribute_by_name('x');
27 my $xtype_constraint = $xattribute->type_constraint;
29 if ( $xtype_constraint->check($xval) ) {
30 $point = Point->new( x => $xval, y => 0 );
33 print "Value: $xval is not an " . $xtype_constraint->name . "\n";
38 This is the Point example from L<Moose::Cookbook::Basics::Recipe1>
39 with type checking added.
41 If we try to assign a string value to an attribute that is an C<Int>,
42 Moose will die with an explicit error message. The error will include
43 the attribute name, as well as the type constraint name and the value
44 which failed the constraint check.
46 We use C<eval> to catch this error message in C<$@>.
48 Later, we get the L<Moose::Meta::TypeConstraint> object from a
49 L<Moose::Meta::Attribute> and use the L<Moose::Meta::TypeConstraint>
50 to check a value directly.
56 =item L<Moose::Cookbook::Basics::Recipe1>
58 =item L<Moose::Utils::TypeConstraints>
60 =item L<Moose::Meta::Attribute>
66 Jess Robinson <cpan@desert-island.me.uk>
68 =head1 COPYRIGHT AND LICENSE
70 Copyright 2006-2010 by Infinity Interactive, Inc.
72 L<http://www.iinteractive.com>
74 This library is free software; you can redistribute it and/or modify
75 it under the same terms as Perl itself.