1Moose::Cookbook::Snack:U:sTeyrpeCso(n3t)ributed Perl DocMuomoesnet:a:tCiooonkbook::Snack::Types(3)
2
3
4

NAME

6       Moose::Cookbook::Snack::Types - Snippets of code for using Types and
7       Type Constraints
8

SYNOPSIS

10         package Point;
11         use Moose;
12
13         has 'x' => ( isa => 'Int', is => 'ro' );
14         has 'y' => ( isa => 'Int', is => 'rw' );
15
16         package main;
17
18         my $point = eval { Point->new( x => 'fifty', y => 'forty' ); };
19
20         if ($@) {
21             print "Oops: $@";
22         }
23
24         my $point;
25         my $xval             = 'forty-two';
26         my $xattribute       = Point->meta->find_attribute_by_name('x');
27         my $xtype_constraint = $xattribute->type_constraint;
28
29         if ( $xtype_constraint->check($xval) ) {
30             $point = Point->new( x => $xval, y => 0 );
31         }
32         else {
33             print "Value: $xval is not an " . $xtype_constraint->name . "\n";
34         }
35

DESCRIPTION

37       This is the Point example from Moose::Cookbook::Basics::Recipe1 with
38       type checking added.
39
40       If we try to assign a string value to an attribute that is an "Int",
41       Moose will die with an explicit error message. The error will include
42       the attribute name, as well as the type constraint name and the value
43       which failed the constraint check.
44
45       We use "eval" to catch this error message in $@.
46
47       Later, we get the Moose::Meta::TypeConstraint object from a
48       Moose::Meta::Attribute and use the Moose::Meta::TypeConstraint to check
49       a value directly.
50

SEE ALSO

52       Moose::Cookbook::Basics::Recipe1
53       Moose::Utils::TypeConstraints
54       Moose::Meta::Attribute
55

AUTHOR

57       Jess Robinson <cpan@desert-island.me.uk>
58
60       Copyright 2006-2010 by Infinity Interactive, Inc.
61
62       <http://www.iinteractive.com>
63
64       This library is free software; you can redistribute it and/or modify it
65       under the same terms as Perl itself.
66
67
68
69perl v5.12.2                      2010-08-21  Moose::Cookbook::Snack::Types(3)
Impressum