6 Moose::Cookbook::Basics::Recipe10 - Operator overloading, subtypes, and coercion
13 use Moose::Util::TypeConstraints;
17 => where { $_ =~ m{^[mf]$}s };
19 has 'gender' => ( is => 'ro', isa => 'Gender', required => 1 );
21 has 'mother' => ( is => 'ro', isa => 'Human' );
22 has 'father' => ( is => 'ro', isa => 'Human' );
24 use overload '+' => \&_overload_add, fallback => 1;
27 my ( $one, $two ) = @_;
29 die('Only male and female humans may create children')
30 if ( $one->gender() eq $two->gender() );
32 my ( $mother, $father )
33 = ( $one->gender eq 'f' ? ( $one, $two ) : ( $two, $one ) );
36 $gender = 'm' if ( rand() >= 0.5 );
47 This Moose cookbook recipe shows how operator overloading, coercion,
48 and sub types can be used to mimic the human reproductive system
49 (well, the selection of genes at least).
53 Our C<Human> class uses operator overloading to allow us to "add" two
54 humans together and produce a child. Our implementation does require
55 that the two objects be of opposite genders. Remember, we're talking
56 about biological reproduction, not marriage.
58 While this example works as-is, we can take it a lot further by adding
59 genes into the mix. We'll add the two genes that control eye color,
60 and use overloading to combine the genes from the parent to model the
63 =head2 What is Operator Overloading?
65 Overloading is I<not> a Moose-specific feature. It's a general OO
66 concept that is implemented in Perl with the C<overload>
67 pragma. Overloading lets objects do something sane when used with
68 Perl's built in operators, like addition (C<+>) or when used as a
71 In this example we overload addition so we can write code like
72 C<$child = $mother + $father>.
76 There are many genes which affect eye color, but there are two which
77 are most important, I<gey> and I<bey2>. We will start by making a
80 =head2 Human::Gene::bey2
82 package Human::Gene::bey2;
85 use Moose::Util::TypeConstraints;
87 type 'bey2_color' => where { $_ =~ m{^(?:brown|blue)$} };
89 has 'color' => ( is => 'ro', isa => 'bey2_color' );
91 This class is trivial, We have a type constraint for the allowed
92 colors, and a C<color> attribute.
94 =head2 Human::Gene::gey
96 package Human::Gene::gey;
99 use Moose::Util::TypeConstraints;
101 type 'gey_color' => where { $_ =~ m{^(?:green|blue)$} };
103 has 'color' => ( is => 'ro', isa => 'gey_color' );
105 This is nearly identical to the C<Humane::Gene::bey2> class, except
106 that the I<gey> gene allows for different colors.
110 We could just give add four attributes (two of each gene) to the
111 C<Human> class, but this is a bit messy. Instead, we'll abstract the
112 genes into a container class, C<Human::EyeColor>. Then a C<Human> can
113 have a single C<eye_color> attribute.
115 package Human::EyeColor;
118 use Moose::Util::TypeConstraints;
120 coerce 'Human::Gene::bey2'
122 => via { Human::Gene::bey2->new( color => $_ ) };
124 coerce 'Human::Gene::gey'
126 => via { Human::Gene::gey->new( color => $_ ) };
128 has [qw( bey2_1 bey2_2 )] =>
129 ( is => 'ro', isa => 'Human::Gene::bey2', coerce => 1 );
131 has [qw( gey_1 gey_2 )] =>
132 ( is => 'ro', isa => 'Human::Gene::gey', coerce => 1 );
134 The eye color class has two of each type of gene. We've also created a
135 coercion for each class that coerces a string into a new object. Note
136 that a coercion will fail if it attempts to coerce a string like
137 "indigo", because that is not a valid color for either type of gene.
139 As an aside, you can see that we can define several identical
140 attributes at once by supply an array reference of names as the first
143 We also need a method to calculate the actual eye color that results
144 from a set of genes. The I<bey2> brown gene is dominant over both blue
145 and green. The I<gey> green gene dominant over blue.
151 if ( $self->bey2_1->color() eq 'brown'
152 or $self->bey2_2->color() eq 'brown' );
155 if ( $self->gey_1->color() eq 'green'
156 or $self->gey_2->color() eq 'green' );
161 We'd like to be able to treat a C<Human::EyeColor> object as a string,
162 so we define a string overloading for the class:
164 use overload '""' => \&color, fallback => 1;
166 Finally, we need to define overloading for addition. That way we can
167 add together to C<Human::EyeColor> objects and get a new one with a
168 new (genetically correct) eye color.
170 use overload '+' => \&_overload_add, fallback => 1;
173 my ( $one, $two ) = @_;
175 my $one_bey2 = 'bey2_' . _rand2();
176 my $two_bey2 = 'bey2_' . _rand2();
178 my $one_gey = 'gey_' . _rand2();
179 my $two_gey = 'gey_' . _rand2();
181 return Human::EyeColor->new(
182 bey2_1 => $one->$one_bey2->color(),
183 bey2_2 => $two->$two_bey2->color(),
184 gey_1 => $one->$one_gey->color(),
185 gey_2 => $two->$two_gey->color(),
190 return 1 + int( rand(2) );
193 When two eye color objects are added together the C<_overload_add()>
194 method will be passed two C<Human::EyeColor> objects. These are the
195 left and right side operands for the C<+> operator. This method
196 returns a new C<Human::EyeColor> object.
198 =head1 ADDING EYE COLOR TO C<Human>s
200 Our original C<Human> class requires just a few changes to incorporate
201 our new C<Human::EyeColor> class.
203 use List::MoreUtils qw( zip );
205 coerce 'Human::EyeColor'
207 => via { my @genes = qw( bey2_1 bey2_2 gey_1 gey_2 );
208 return Human::EyeColor->new( zip( @genes, @{$_} ) ); };
212 isa => 'Human::EyeColor',
217 We also need to modify C<_overload_add()> in the C<Human> class to
218 account for eye color:
222 eye_color => ( $one->eye_color() + $two->eye_color() ),
229 The three techniques we used, overloading, subtypes, and coercion,
230 combine to provide a powerful interface.
232 If you'd like to learn more about overloading, please read the
233 documentation for the L<overload> pragma.
235 To see all the code we created together, take a look at
236 F<t/000_recipes/basics/010_genes.t>.
240 Has this been a real project we'd probably want to:
244 =item Better Randomization with Crypt::Random
246 =item Characteristic Base Class
250 =item More Characteristics
252 =item Artificial Life
258 Aran Clary Deltac <bluefeet@cpan.org>
260 Dave Rolsky E<lt>autarch@urth.orgE<gt>
264 This work is licensed under a Creative Commons Attribution 3.0 Unported License.
266 License details are at: L<http://creativecommons.org/licenses/by/3.0/>