Moose::...oercion(3)

🌸 Moose::Cookbook::Basics::Genome_OverloadingSubtypesAndCoercion 🌸

okay bestie, you opened Moose::...oercion(3) and honestly? iconic choice. this page is literally called Operator overloading, subtypes, and coercion and it's a Moose cookbook recipe. buckle up. πŸ’–


✨ VERSION ✨

version 2.4000

no cap. that's the version. moving on. πŸ¦‹


πŸ’… SYNOPSIS πŸ’…

package Human;

use Moose;
use Moose::Util::TypeConstraints;

subtype 'Sex'
    => as 'Str'
    => where { $_ =~ m{^[mf]$}s };

has 'sex'    => ( is => 'ro', isa => 'Sex', required => 1 );

has 'mother' => ( is => 'ro', isa => 'Human' );
has 'father' => ( is => 'ro', isa => 'Human' );

use overload '+' => \&_overload_add, fallback => 1;

sub _overload_add {
    my ( $one, $two ) = @_;

    die('Only male and female humans may create children')
        if ( $one->sex() eq $two->sex() );

    my ( $mother, $father )
        = ( $one->sex eq 'f' ? ( $one, $two ) : ( $two, $one ) );

    my $sex = 'f';
    $sex = 'm' if ( rand() >= 0.5 );

    return Human->new(
        sex    => $sex,
        mother => $mother,
        father => $father,
    );
}

🧬 DESCRIPTION 🧬

so 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. 😭 it's giving biology class but make it Moose.


πŸ‘‘ 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. lowkey genius.

🌈 What is Operator Overloading? 🌈

overloading is not a Moose-specific feature, bestie. 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. main character energy fr fr.


πŸ¦‹ 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::bey2 ⭐

package Human::Gene::bey2;

use Moose;
use Moose::Util::TypeConstraints;

type 'bey2_color' => where { $_ =~ m{^(?:brown|blue)$} };

has 'color' => ( is => 'ro', isa => 'bey2_color' );

this class is trivial. we have a type constraint for the allowed colors, and a color attribute. simple, clean, slay. πŸ’…

πŸ“ Human::Gene::gey πŸ“

package Human::Gene::gey;

use Moose;
use Moose::Util::TypeConstraints;

type 'gey_color' => where { $_ =~ m{^(?:green|blue)$} };

has 'color' => ( is => 'ro', isa => 'gey_color' );

this is nearly identical to the Humane::Gene::bey2 class, except that the gey gene allows for different colors. (yes, that spelling is what the original says. not me fixing it. we keep the facts, always. πŸ’–)


πŸŽ€ 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. so much tidier, we love a glow-up. ✨

package Human::EyeColor;

use Moose;
use Moose::Util::TypeConstraints;

coerce 'Human::Gene::bey2'
    => from 'Str'
        => via { Human::Gene::bey2->new( color => $_ ) };

coerce 'Human::Gene::gey'
    => from 'Str'
        => via { Human::Gene::gey->new( color => $_ ) };

has [qw( bey2_1 bey2_2 )] =>
    ( is => 'ro', isa => 'Human::Gene::bey2', coerce => 1 );

has [qw( gey_1 gey_2 )] =>
    ( is => 'ro', isa => 'Human::Gene::gey', coerce => 1 );

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. so don't try it, it's not that girl. πŸ™ˆ

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. cute trick, iykyk.

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. genetics said "here's the hierarchy." πŸ’…

sub color {
    my ($self) = @_;

    return 'brown'
        if ( $self->bey2_1->color() eq 'brown'
        or $self->bey2_2->color() eq 'brown' );

    return 'green'
        if ( $self->gey_1->color() eq 'green'
        or $self->gey_2->color() eq 'green' );

    return 'blue';
}

we'd like to be able to treat a Human::EyeColor object as a string, so we define a string overloading for the class:

use overload '""' => \&color, fallback => 1;

finally, we need to define overloading for addition. that way we can add together two Human::EyeColor objects and get a new one with a new (genetically correct) eye color. 🧬✨

use overload '+' => \&_overload_add, fallback => 1;

sub _overload_add {
    my ( $one, $two ) = @_;

    my $one_bey2 = 'bey2_' . _rand2();
    my $two_bey2 = 'bey2_' . _rand2();

    my $one_gey = 'gey_' . _rand2();
    my $two_gey = 'gey_' . _rand2();

    return Human::EyeColor->new(
        bey2_1 => $one->$one_bey2->color(),
        bey2_2 => $two->$two_bey2->color(),
        gey_1  => $one->$one_gey->color(),
        gey_2  => $two->$two_gey->color(),
    );
}

sub _rand2 {
    return 1 + int( rand(2) );
}

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. periodt. πŸ”₯


🌈 ADDING EYE COLOR TO "Human"s 🌈

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

use List::Util 1.56 qw( mesh );

coerce 'Human::EyeColor'
    => from 'ArrayRef'
    => via { my @genes = qw( bey2_1 bey2_2 gey_1 gey_2 );
             return Human::EyeColor->new( mesh ( \@genes, $_ ) ); };

has 'eye_color' => (
    is       => 'ro',
    isa      => 'Human::EyeColor',
    coerce   => 1,
    required => 1,
);

we also need to modify _overload_add() in the Human class to account for eye color:

return Human->new(
    sex       => $sex,
    eye_color => ( $one->eye_color() + $two->eye_color() ),
    mother    => $mother,
    father    => $father,
);

πŸ’– CONCLUSION πŸ’–

the three techniques we used β€” overloading, subtypes, and coercion β€” combine to provide a powerful interface. it's giving three icons in one. 😭

if you'd like to learn more about overloading, please read the documentation for the overload pragma. go read it, bestie. πŸ“š

to see all the code we created together, take a look at t/recipes/basics_genome_overloadingsubtypesandcoercion.t. it's all there. 🫢


⭐ NEXT STEPS ⭐

had this been a real project we'd probably want:

  • Better Randomization with Crypt::Random
  • Characteristic Base Class
  • Mutating Genes
  • More Characteristics
  • Artificial Life

the way this list is giving "we could go further but we're keeping it a recipe." πŸ’€


πŸ‘‘ AUTHORS πŸ‘‘

  • Stevan Little <stevan@cpan.org>
  • Dave Rolsky <autarch@urth.org>
  • Jesse Luehrs <doy@cpan.org>
  • Shawn M Moore <sartak@cpan.org>
  • Χ™Χ•Χ‘Χœ Χ§Χ•Χ’'מן (Yuval Kogman) <nothingmuch@woobling.org>
  • Karen Etheridge <ether@cpan.org>
  • Florian Ragwitz <rafl@debian.org>
  • Hans Dieter Pearcey <hdp@cpan.org>
  • Chris Prather <chris@prather.org>
  • Matt S Trout <mstrout@cpan.org>

all of them. legends. πŸ’…


this work is licensed under a Creative Commons Attribution 3.0 Unported License. πŸ“œ

license details are at: <http://creativecommons.org/licenses/by/3.0/>


and that's the whole page, bestie!! no details skipped, no cap. πŸ’–

mwah πŸ’‹ this was perl v5.42.0, dated 2025-07-25, and the manual you just read is Moose::...oercion(3). take care of her, she's an icon. βœ¨πŸŒΈπŸ¦‹

πŸ“¦ where this page comes from