{
    "content": [
        {
            "type": "text",
            "text": "# Moose::Manual::Types (perldoc)\n\n## NAME\n\nMoose::Manual::Types - Moose's type system\n\n## Sections\n\n- **NAME**\n- **VERSION**\n- **THE TYPES**\n- **SUBTYPES** (1 subsections)\n- **TYPE NAMES**\n- **COERCION** (1 subsections)\n- **TYPE UNIONS**\n- **TYPE CREATION HELPERS**\n- **ANONYMOUS TYPES**\n- **VALIDATING METHOD PARAMETERS**\n- **LOAD ORDER ISSUES**\n- **AUTHORS**\n- **COPYRIGHT AND LICENSE**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "Moose::Manual::Types",
        "section": "",
        "mode": "perldoc",
        "summary": "Moose::Manual::Types - Moose's type system",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "VERSION",
                "lines": 21,
                "subsections": []
            },
            {
                "name": "THE TYPES",
                "lines": 97,
                "subsections": []
            },
            {
                "name": "SUBTYPES",
                "lines": 3,
                "subsections": [
                    {
                        "name": "parent",
                        "lines": 21
                    }
                ]
            },
            {
                "name": "TYPE NAMES",
                "lines": 24,
                "subsections": []
            },
            {
                "name": "COERCION",
                "lines": 31,
                "subsections": [
                    {
                        "name": "Deep coercion",
                        "lines": 46
                    }
                ]
            },
            {
                "name": "TYPE UNIONS",
                "lines": 54,
                "subsections": []
            },
            {
                "name": "TYPE CREATION HELPERS",
                "lines": 11,
                "subsections": []
            },
            {
                "name": "ANONYMOUS TYPES",
                "lines": 11,
                "subsections": []
            },
            {
                "name": "VALIDATING METHOD PARAMETERS",
                "lines": 38,
                "subsections": []
            },
            {
                "name": "LOAD ORDER ISSUES",
                "lines": 6,
                "subsections": []
            },
            {
                "name": "AUTHORS",
                "lines": 20,
                "subsections": []
            },
            {
                "name": "COPYRIGHT AND LICENSE",
                "lines": 5,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "Moose::Manual::Types - Moose's type system\n",
                "subsections": []
            },
            "VERSION": {
                "content": "version 2.2200\n\nTYPES IN PERL?\nMoose provides its own type system for attributes. You can also use these types to validate\nmethod parameters with the help of a MooseX module.\n\nMoose's type system is based on a combination of Perl 5's own *implicit* types and some Perl 6\nconcepts. You can create your own subtypes with custom constraints, making it easy to express\nany sort of validation.\n\nTypes have names, and you can re-use them by name, making it easy to share types throughout a\nlarge application.\n\nHowever, this is not a \"real\" type system. Moose does not magically make Perl start associating\ntypes with variables. This is just an advanced parameter checking system which allows you to\nassociate a name with a constraint.\n\nThat said, it's still pretty damn useful, and we think it's one of the things that makes Moose\nboth fun and powerful. Taking advantage of the type system makes it much easier to ensure that\nyou are getting valid data, and it also contributes greatly to code maintainability.\n",
                "subsections": []
            },
            "THE TYPES": {
                "content": "The basic Moose type hierarchy looks like this\n\nAny\nItem\nBool\nMaybe[`a]\nUndef\nDefined\nValue\nStr\nNum\nInt\nClassName\nRoleName\nRef\nScalarRef[`a]\nArrayRef[`a]\nHashRef[`a]\nCodeRef\nRegexpRef\nGlobRef\nFileHandle\nObject\n\nIn practice, the only difference between \"Any\" and \"Item\" is conceptual. \"Item\" is used as the\ntop-level type in the hierarchy.\n\nThe rest of these types correspond to existing Perl concepts. In particular:\n\n*   \"Bool\" accepts 1 for true, and undef, 0, or the empty string as false.\n\n*   \"Maybe[`a]\" accepts either \"`a\" or \"undef\".\n\n*   \"Num\" accepts integers, floating point numbers (both in decimal notation & exponential\nnotation), 0, .0, 0.0 etc. It doesn't accept numbers with whitespace, Inf, Infinity, \"0 but\ntrue\", NaN & other such strings.\n\n*   \"ClassName\" and \"RoleName\" accept strings that are either the name of a class or the name of\na role. The class/role must already be loaded when the constraint is checked.\n\n*   \"FileHandle\" accepts either an IO::Handle object or a builtin perl filehandle (see\n\"openhandle\" in Scalar::Util).\n\n*   \"Object\" accepts any blessed reference.\n\nThe types followed by \"[`a]\" can be parameterized. So instead of just plain \"ArrayRef\" we can\nsay that we want \"ArrayRef[Int]\" instead. We can even do something like\n\"HashRef[ArrayRef[Str]]\".\n\nThe \"Maybe[`a]\" type deserves a special mention. Used by itself, it doesn't really mean anything\n(and is equivalent to \"Item\"). When it is parameterized, it means that the value is either\n\"undef\" or the parameterized type. So \"Maybe[Int]\" means an integer or \"undef\".\n\nFor more details on the type hierarchy, see Moose::Util::TypeConstraints.\n\nWHAT IS A TYPE?\nIt's important to realize that types are not classes (or packages). Types are just objects\n(Moose::Meta::TypeConstraint objects, to be exact) with a name and a constraint. Moose maintains\na global type registry that lets it convert names like \"Num\" into the appropriate object.\n\nHowever, class names *can be* type names. When you define a new class using Moose, it defines an\nassociated type name behind the scenes:\n\npackage MyApp::User;\n\nuse Moose;\n\nNow you can use 'MyApp::User' as a type name:\n\nhas creator => (\nis  => 'ro',\nisa => 'MyApp::User',\n);\n\nHowever, for non-Moose classes there's no magic. You may have to explicitly declare the class\ntype. This is a bit muddled because Moose assumes that any unknown type name passed as the \"isa\"\nvalue for an attribute is a class. So this works:\n\nhas 'birthdate' => (\nis  => 'ro',\nisa => 'DateTime',\n);\n\nIn general, when Moose is presented with an unknown name, it assumes that the name is a class:\n\nsubtype 'ModernDateTime'\n=> as 'DateTime'\n=> where { $->year() >= 1980 }\n=> message { 'The date you provided is not modern enough' };\n\nhas 'validdates' => (\nis  => 'ro',\nisa => 'ArrayRef[DateTime]',\n);\n\nMoose will assume that \"DateTime\" is a class name in both of these instances.\n",
                "subsections": []
            },
            "SUBTYPES": {
                "content": "Moose uses subtypes in its built-in hierarchy. For example, \"Int\" is a child of \"Num\".\n\nA subtype is defined in terms of a parent type and a constraint. Any constraints defined by the",
                "subsections": [
                    {
                        "name": "parent",
                        "content": "pass *all* of these checks to be valid for the subtype.\n\nTypically, a subtype takes the parent's constraint and makes it more specific.\n\nA subtype can also define its own constraint failure message. This lets you do things like have\nan error \"The value you provided (20), was not a valid rating, which must be a number from\n1-10.\" This is much friendlier than the default error, which just says that the value failed a\nvalidation check for the type. The default error can, however, be made more friendly by\ninstalling Devel::PartialDump (version 0.14 or higher), which Moose will use if possible to\ndisplay the invalid value.\n\nHere's a simple (and useful) subtype example:\n\nsubtype 'PositiveInt',\nas 'Int',\nwhere { $ > 0 },\nmessage { \"The number you provided, $, was not a positive number\" };\n\nNote that the sugar functions for working with types are all exported by\nMoose::Util::TypeConstraints.\n"
                    }
                ]
            },
            "TYPE NAMES": {
                "content": "Type names are global throughout the current Perl interpreter. Internally, Moose maps names to\ntype objects via a registry.\n\nIf you have multiple apps or libraries all using Moose in the same process, you could have\nproblems with collisions. We recommend that you prefix names with some sort of namespace\nindicator to prevent these sorts of collisions.\n\nFor example, instead of calling a type \"PositiveInt\", call it \"MyApp::Type::PositiveInt\" or\n\"MyApp::Types::PositiveInt\". We recommend that you centralize all of these definitions in a\nsingle package, \"MyApp::Types\", which can be loaded by other classes in your application.\n\nHowever, before you do this, you should look at the MooseX::Types module. This module makes it\neasy to create a \"type library\" module, which can export your types as perl constants.\n\nhas 'counter' => (is => 'rw', isa => PositiveInt);\n\nThis lets you use a short name rather than needing to fully qualify the name everywhere. It also\nallows you to easily create parameterized types:\n\nhas 'counts' => (is => 'ro', isa => HashRef[PositiveInt]);\n\nThis module will check your names at compile time, and is generally more robust than the string\ntype parsing for complex cases.\n",
                "subsections": []
            },
            "COERCION": {
                "content": "A coercion lets you tell Moose to automatically convert one type to another.\n\nsubtype 'ArrayRefOfInts',\nas 'ArrayRef[Int]';\n\ncoerce 'ArrayRefOfInts',\nfrom 'Int',\nvia { [ $ ] };\n\nYou'll note that we created a subtype rather than coercing \"ArrayRef[Int]\" directly. It's a bad\nidea to add coercions to the raw built in types.\n\nCoercions are global, just like type names, so a coercion applied to a built in type is seen by\nall modules using Moose types. This is *another* reason why it is good to namespace your types.\n\nMoose will *never* try to coerce a value unless you explicitly ask for it. This is done by\nsetting the \"coerce\" attribute option to a true value:\n\npackage Foo;\n\nhas 'sizes' => (\nis     => 'ro',\nisa    => 'ArrayRefOfInts',\ncoerce => 1,\n);\n\nFoo->new( sizes => 42 );\n\nThis code example will do the right thing, and the newly created object will have \"[ 42 ]\" as\nits \"sizes\" attribute.\n",
                "subsections": [
                    {
                        "name": "Deep coercion",
                        "content": "Deep coercion is the coercion of type parameters for parameterized types. Let's take these types\nas an example:\n\nsubtype 'HexNum',\nas 'Str',\nwhere { /[a-f0-9]/i };\n\ncoerce 'Int',\nfrom 'HexNum',\nvia { hex $ };\n\nhas 'sizes' => (\nis     => 'ro',\nisa    => 'ArrayRef[Int]',\ncoerce => 1,\n);\n\nIf we try passing an array reference of hex numbers for the \"sizes\" attribute, Moose will not do\nany coercion.\n\nHowever, you can define a set of subtypes to enable coercion between two parameterized types.\n\nsubtype 'ArrayRefOfHexNums',\nas 'ArrayRef[HexNum]';\n\nsubtype 'ArrayRefOfInts',\nas 'ArrayRef[Int]';\n\ncoerce 'ArrayRefOfInts',\nfrom 'ArrayRefOfHexNums',\nvia { [ map { hex } @{$} ] };\n\nFoo->new( sizes => [ 'a1', 'ff', '22' ] );\n\nNow Moose will coerce the hex numbers to integers.\n\nMoose does not attempt to chain coercions, so it will not coerce a single hex number. To do\nthat, we need to define a separate coercion:\n\ncoerce 'ArrayRefOfInts',\nfrom 'HexNum',\nvia { [ hex $ ] };\n\nYes, this can all get verbose, but coercion is tricky magic, and we think it's best to make it\nexplicit.\n"
                    }
                ]
            },
            "TYPE UNIONS": {
                "content": "Moose allows you to say that an attribute can be of two or more disparate types. For example, we\nmight allow an \"Object\" or \"FileHandle\":\n\nhas 'output' => (\nis  => 'rw',\nisa => 'Object | FileHandle',\n);\n\nMoose actually parses that string and recognizes that you are creating a type union. The\n\"output\" attribute will accept any sort of object, as well as an unblessed file handle. It is up\nto you to do the right thing for each of them in your code.\n\nWhenever you use a type union, you should consider whether or not coercion might be a better\nanswer.\n\nFor our example above, we might want to be more specific, and insist that output be an object\nwith a \"print\" method:\n\nducktype 'CanPrint', [qw(print)];\n\nWe can coerce file handles to an object that satisfies this condition with a simple wrapper\nclass:\n\npackage FHWrapper;\n\nuse Moose;\n\nhas 'handle' => (\nis  => 'rw',\nisa => 'FileHandle',\n);\n\nsub print {\nmy $self = shift;\nmy $fh   = $self->handle();\n\nprint {$fh} @;\n}\n\nNow we can define a coercion from \"FileHandle\" to our wrapper class:\n\ncoerce 'CanPrint'\n=> from 'FileHandle'\n=> via { FHWrapper->new( handle => $ ) };\n\nhas 'output' => (\nis     => 'rw',\nisa    => 'CanPrint',\ncoerce => 1,\n);\n\nThis pattern of using a coercion instead of a type union will help make your class internals\nsimpler.\n",
                "subsections": []
            },
            "TYPE CREATION HELPERS": {
                "content": "The Moose::Util::TypeConstraints module exports a number of helper functions for creating\nspecific kinds of types. These include \"classtype\", \"roletype\", \"maybetype\", and \"ducktype\".\nSee the docs for details.\n\nOne helper worth noting is \"enum\", which allows you to create a subtype of \"Str\" that only\nallows the specified values:\n\nenum 'RGB', [qw( red green blue )];\n\nThis creates a type named \"RGB\".\n",
                "subsections": []
            },
            "ANONYMOUS TYPES": {
                "content": "All of the type creation functions return a type object. This type object can be used wherever\nyou would use a type name, as a parent type, or as the value for an attribute's \"isa\" option:\n\nhas 'size' => (\nis  => 'ro',\nisa => subtype( 'Int' => where { $ > 0 } ),\n);\n\nThis is handy when you want to create a one-off type and don't want to \"pollute\" the global\nnamespace registry.\n",
                "subsections": []
            },
            "VALIDATING METHOD PARAMETERS": {
                "content": "Moose does not provide any means of validating method parameters. However, there are several\nMooseX extensions on CPAN which let you do this.\n\nThe simplest and least sugary is Params::ValidationCompiler. This lets you validate a set of\nnamed parameters using Moose types:\n\nuse Moose::Util::TypeConstraints qw( findtypeconstraint );\nuse Params::ValidationCompiler qw( validationfor );\n\n{\nmy $validator = validationfor(\nparams => {\nfoo => { type => findtypeconstraint('Int') },\nbar => {\ntype     => findtypeconstraint('Str'),\noptional => 1,\n},\nbaz => {\ntype    => findtypeconstraint('Int'),\ndefault => 42,\n},\n},\n);\n\nsub foo {\nmy %args = $validator->(@);\n}\n}\n\nParams::ValidationCompiler also supports coercions.\n\nThere are several more powerful extensions that support method parameter validation using Moose\ntypes, including Moops, which gives you a full-blown \"method\" keyword.\n\nmethod morning ( Str $name ) {\n$self->say(\"Good morning ${name}!\");\n}\n",
                "subsections": []
            },
            "LOAD ORDER ISSUES": {
                "content": "Because Moose types are defined at runtime, you may run into load order problems. In particular,\nyou may want to use a class's type constraint before that type has been defined.\n\nIn order to ameliorate this problem, we recommend defining *all* of your custom types in one\nmodule, \"MyApp::Types\", and then loading this module in all of your other modules.\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 software is copyright (c) 2006 by Infinity Interactive, Inc.\n\nThis is free software; you can redistribute it and/or modify it under the same terms as the Perl\n5 programming language system itself.\n",
                "subsections": []
            }
        }
    }
}