{
    "content": [
        {
            "type": "text",
            "text": "# Moose::Cookbook::Basics::Genome_OverloadingSubtypesAndCoercion (perldoc)\n\n## NAME\n\nMoose::Cookbook::Basics::GenomeOverloadingSubtypesAndCoercion - Operator overloading, subtypes, and coercion\n\n## SYNOPSIS\n\npackage Human;\nuse Moose;\nuse Moose::Util::TypeConstraints;\nsubtype 'Sex'\n=> as 'Str'\n=> where { $ =~ m{^[mf]$}s };\nhas 'sex'    => ( is => 'ro', isa => 'Sex', required => 1 );\nhas 'mother' => ( is => 'ro', isa => 'Human' );\nhas 'father' => ( is => 'ro', isa => 'Human' );\nuse overload '+' => \\&overloadadd, fallback => 1;\nsub overloadadd {\nmy ( $one, $two ) = @;\ndie('Only male and female humans may create children')\nif ( $one->sex() eq $two->sex() );\nmy ( $mother, $father )\n= ( $one->sex eq 'f' ? ( $one, $two ) : ( $two, $one ) );\nmy $sex = 'f';\n$sex = 'm' if ( rand() >= 0.5 );\nreturn Human->new(\nsex    => $sex,\nmother => $mother,\nfather => $father,\n);\n}\n\n## DESCRIPTION\n\nThis Moose cookbook recipe shows how operator overloading, coercion, and subtypes can be used to\nmimic the human reproductive system (well, the selection of genes at least).\n\n## Sections\n\n- **NAME**\n- **VERSION**\n- **SYNOPSIS**\n- **DESCRIPTION**\n- **INTRODUCTION**\n- **GENES** (2 subsections)\n- **EYE COLOR**\n- **CONCLUSION**\n- **NEXT STEPS**\n- **AUTHORS**\n- **COPYRIGHT AND LICENSE**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "Moose::Cookbook::Basics::Genome_OverloadingSubtypesAndCoercion",
        "section": "",
        "mode": "perldoc",
        "summary": "Moose::Cookbook::Basics::GenomeOverloadingSubtypesAndCoercion - Operator overloading, subtypes, and coercion",
        "synopsis": "package Human;\nuse Moose;\nuse Moose::Util::TypeConstraints;\nsubtype 'Sex'\n=> as 'Str'\n=> where { $ =~ m{^[mf]$}s };\nhas 'sex'    => ( is => 'ro', isa => 'Sex', required => 1 );\nhas 'mother' => ( is => 'ro', isa => 'Human' );\nhas 'father' => ( is => 'ro', isa => 'Human' );\nuse overload '+' => \\&overloadadd, fallback => 1;\nsub overloadadd {\nmy ( $one, $two ) = @;\ndie('Only male and female humans may create children')\nif ( $one->sex() eq $two->sex() );\nmy ( $mother, $father )\n= ( $one->sex eq 'f' ? ( $one, $two ) : ( $two, $one ) );\nmy $sex = 'f';\n$sex = 'm' if ( rand() >= 0.5 );\nreturn Human->new(\nsex    => $sex,\nmother => $mother,\nfather => $father,\n);\n}",
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 3,
                "subsections": []
            },
            {
                "name": "VERSION",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 35,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 3,
                "subsections": []
            },
            {
                "name": "INTRODUCTION",
                "lines": 15,
                "subsections": []
            },
            {
                "name": "GENES",
                "lines": 3,
                "subsections": [
                    {
                        "name": "Human::Gene::bey2",
                        "lines": 12
                    },
                    {
                        "name": "Human::Gene::gey",
                        "lines": 12
                    }
                ]
            },
            {
                "name": "EYE COLOR",
                "lines": 110,
                "subsections": []
            },
            {
                "name": "CONCLUSION",
                "lines": 9,
                "subsections": []
            },
            {
                "name": "NEXT STEPS",
                "lines": 8,
                "subsections": []
            },
            {
                "name": "AUTHORS",
                "lines": 20,
                "subsections": []
            },
            {
                "name": "COPYRIGHT AND LICENSE",
                "lines": 4,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "Moose::Cookbook::Basics::GenomeOverloadingSubtypesAndCoercion - Operator overloading, subtypes,\nand coercion\n",
                "subsections": []
            },
            "VERSION": {
                "content": "version 2.2200\n",
                "subsections": []
            },
            "SYNOPSIS": {
                "content": "package Human;\n\nuse Moose;\nuse Moose::Util::TypeConstraints;\n\nsubtype 'Sex'\n=> as 'Str'\n=> where { $ =~ m{^[mf]$}s };\n\nhas 'sex'    => ( is => 'ro', isa => 'Sex', required => 1 );\n\nhas 'mother' => ( is => 'ro', isa => 'Human' );\nhas 'father' => ( is => 'ro', isa => 'Human' );\n\nuse overload '+' => \\&overloadadd, fallback => 1;\n\nsub overloadadd {\nmy ( $one, $two ) = @;\n\ndie('Only male and female humans may create children')\nif ( $one->sex() eq $two->sex() );\n\nmy ( $mother, $father )\n= ( $one->sex eq 'f' ? ( $one, $two ) : ( $two, $one ) );\n\nmy $sex = 'f';\n$sex = 'm' if ( rand() >= 0.5 );\n\nreturn Human->new(\nsex    => $sex,\nmother => $mother,\nfather => $father,\n);\n}\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "This Moose cookbook recipe shows how operator overloading, coercion, and subtypes can be used to\nmimic the human reproductive system (well, the selection of genes at least).\n",
                "subsections": []
            },
            "INTRODUCTION": {
                "content": "Our \"Human\" class uses operator overloading to allow us to \"add\" two humans together and produce\na child. Our implementation does require that the two objects be of opposite sex. Remember,\nwe're talking about biological reproduction, not marriage.\n\nWhile this example works as-is, we can take it a lot further by adding genes into the mix. We'll\nadd the two genes that control eye color, and use overloading to combine the genes from the\nparent to model the biology.\n\nWhat is Operator Overloading?\nOverloading is *not* a Moose-specific feature. It's a general OO concept that is implemented in\nPerl with the \"overload\" pragma. Overloading lets objects do something sane when used with\nPerl's built in operators, like addition (\"+\") or when used as a string.\n\nIn this example we overload addition so we can write code like \"$child = $mother + $father\".\n",
                "subsections": []
            },
            "GENES": {
                "content": "There are many genes which affect eye color, but there are two which are most important, *gey*\nand *bey2*. We will start by making a class for each gene.\n",
                "subsections": [
                    {
                        "name": "Human::Gene::bey2",
                        "content": "package Human::Gene::bey2;\n\nuse Moose;\nuse Moose::Util::TypeConstraints;\n\ntype 'bey2color' => where { $ =~ m{^(?:brown|blue)$} };\n\nhas 'color' => ( is => 'ro', isa => 'bey2color' );\n\nThis class is trivial. We have a type constraint for the allowed colors, and a \"color\"\nattribute.\n"
                    },
                    {
                        "name": "Human::Gene::gey",
                        "content": "package Human::Gene::gey;\n\nuse Moose;\nuse Moose::Util::TypeConstraints;\n\ntype 'geycolor' => where { $ =~ m{^(?:green|blue)$} };\n\nhas 'color' => ( is => 'ro', isa => 'geycolor' );\n\nThis is nearly identical to the \"Humane::Gene::bey2\" class, except that the *gey* gene allows\nfor different colors.\n"
                    }
                ]
            },
            "EYE COLOR": {
                "content": "We could just give four attributes (two of each gene) to the \"Human\" class, but this is a bit\nmessy. Instead, we'll abstract the genes into a container class, \"Human::EyeColor\". Then a\n\"Human\" can have a single \"eyecolor\" attribute.\n\npackage Human::EyeColor;\n\nuse Moose;\nuse Moose::Util::TypeConstraints;\n\ncoerce 'Human::Gene::bey2'\n=> from 'Str'\n=> via { Human::Gene::bey2->new( color => $ ) };\n\ncoerce 'Human::Gene::gey'\n=> from 'Str'\n=> via { Human::Gene::gey->new( color => $ ) };\n\nhas [qw( bey21 bey22 )] =>\n( is => 'ro', isa => 'Human::Gene::bey2', coerce => 1 );\n\nhas [qw( gey1 gey2 )] =>\n( is => 'ro', isa => 'Human::Gene::gey', coerce => 1 );\n\nThe eye color class has two of each type of gene. We've also created a coercion for each class\nthat coerces a string into a new object. Note that a coercion will fail if it attempts to coerce\na string like \"indigo\", because that is not a valid color for either type of gene.\n\nAs an aside, you can see that we can define several identical attributes at once by supplying an\narray reference of names as the first argument to \"has\".\n\nWe also need a method to calculate the actual eye color that results from a set of genes. The\n*bey2* brown gene is dominant over both blue and green. The *gey* green gene is dominant over\nblue.\n\nsub color {\nmy ($self) = @;\n\nreturn 'brown'\nif ( $self->bey21->color() eq 'brown'\nor $self->bey22->color() eq 'brown' );\n\nreturn 'green'\nif ( $self->gey1->color() eq 'green'\nor $self->gey2->color() eq 'green' );\n\nreturn 'blue';\n}\n\nWe'd like to be able to treat a \"Human::EyeColor\" object as a string, so we define a string\noverloading for the class:\n\nuse overload '\"\"' => \\&color, fallback => 1;\n\nFinally, we need to define overloading for addition. That way we can add together two\n\"Human::EyeColor\" objects and get a new one with a new (genetically correct) eye color.\n\nuse overload '+' => \\&overloadadd, fallback => 1;\n\nsub overloadadd {\nmy ( $one, $two ) = @;\n\nmy $onebey2 = 'bey2' . rand2();\nmy $twobey2 = 'bey2' . rand2();\n\nmy $onegey = 'gey' . rand2();\nmy $twogey = 'gey' . rand2();\n\nreturn Human::EyeColor->new(\nbey21 => $one->$onebey2->color(),\nbey22 => $two->$twobey2->color(),\ngey1  => $one->$onegey->color(),\ngey2  => $two->$twogey->color(),\n);\n}\n\nsub rand2 {\nreturn 1 + int( rand(2) );\n}\n\nWhen two eye color objects are added together, the \"overloadadd()\" method will be passed two\n\"Human::EyeColor\" objects. These are the left and right side operands for the \"+\" operator. This\nmethod returns a new \"Human::EyeColor\" object.\n\nADDING EYE COLOR TO \"Human\"s\nOur original \"Human\" class requires just a few changes to incorporate our new \"Human::EyeColor\"\nclass.\n\nuse List::Util 1.56 qw( mesh );\n\ncoerce 'Human::EyeColor'\n=> from 'ArrayRef'\n=> via { my @genes = qw( bey21 bey22 gey1 gey2 );\nreturn Human::EyeColor->new( mesh ( \\@genes, $ ) ); };\n\nhas 'eyecolor' => (\nis       => 'ro',\nisa      => 'Human::EyeColor',\ncoerce   => 1,\nrequired => 1,\n);\n\nWe also need to modify \"overloadadd()\" in the \"Human\" class to account for eye color:\n\nreturn Human->new(\nsex       => $sex,\neyecolor => ( $one->eyecolor() + $two->eyecolor() ),\nmother    => $mother,\nfather    => $father,\n);\n",
                "subsections": []
            },
            "CONCLUSION": {
                "content": "The three techniques we used, overloading, subtypes, and coercion, combine to provide a powerful\ninterface.\n\nIf you'd like to learn more about overloading, please read the documentation for the overload\npragma.\n\nTo see all the code we created together, take a look at\nt/recipes/basicsgenomeoverloadingsubtypesandcoercion.t.\n",
                "subsections": []
            },
            "NEXT STEPS": {
                "content": "Had this been a real project we'd probably want:\n\nBetter Randomization with Crypt::Random\nCharacteristic Base Class\nMutating Genes\nMore Characteristics\nArtificial Life\n",
                "subsections": []
            },
            "AUTHORS": {
                "content": "*   Stevan Little <stevan@cpan.org>\n\n*   Dave Rolsky <autarch@urth.org>\n\n*   Jesse Luehrs <doy@cpan.org>\n\n*   Shawn M Moore <sartak@cpan.org>\n\n*   יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>\n\n*   Karen Etheridge <ether@cpan.org>\n\n*   Florian Ragwitz <rafl@debian.org>\n\n*   Hans Dieter Pearcey <hdp@cpan.org>\n\n*   Chris Prather <chris@prather.org>\n\n*   Matt S Trout <mstrout@cpan.org>\n",
                "subsections": []
            },
            "COPYRIGHT AND LICENSE": {
                "content": "This work is licensed under a Creative Commons Attribution 3.0 Unported License.\n\nLicense details are at: <http://creativecommons.org/licenses/by/3.0/>\n",
                "subsections": []
            }
        }
    }
}