DESCRIPTION

This Moose cookbook recipe shows how operator overloading, coercion, and subtypes can be used to mimic the human reproductive system (well, the selection of genes at least).

INTRODUCTION

Our Human class uses operator overloading to allow us to "add" two humans together and produce a child. Our implementation does require that the two objects be of opposite sex. Remember, we're talking about biological reproduction, not marriage.

While this example works as-is, we can take it a lot further by adding genes into the mix. We'll add the two genes that control eye color, and use overloading to combine the genes from the parent to model the biology.

What is Operator Overloading?

Overloading is not a Moose-specific feature. It's a general OO concept that is implemented in Perl with the overload pragma. Overloading lets objects do something sane when used with Perl's built in operators, like addition (+) or when used as a string.

In this example we overload addition so we can write code like $child = $mother + $father.

GENES

There are many genes which affect eye color, but there are two which are most important, gey and bey2. We will start by making a class for each gene.

Human::Gene::gey

This is nearly identical to the Humane::Gene::bey2 class, except that the gey gene allows for different colors.

EYE COLOR

We could just give four attributes (two of each gene) to the Human class, but this is a bit messy. Instead, we'll abstract the genes into a container class, Human::EyeColor. Then a Human can have a single eye_color attribute.

The eye color class has two of each type of gene. We've also created a coercion for each class that coerces a string into a new object. Note that a coercion will fail if it attempts to coerce a string like "indigo", because that is not a valid color for either type of gene.

As an aside, you can see that we can define several identical attributes at once by supplying an array reference of names as the first argument to has.

We also need a method to calculate the actual eye color that results from a set of genes. The bey2 brown gene is dominant over both blue and green. The gey green gene is dominant over blue.

When two eye color objects are added together, the _overload_add() method will be passed two Human::EyeColor objects. These are the left and right side operands for the + operator. This method returns a new Human::EyeColor object.

ADDING EYE COLOR TO Humans

Our original Human class requires just a few changes to incorporate our new Human::EyeColor class.