{
    "mode": "perldoc",
    "parameter": "Moose::Util::TypeConstraints",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Moose%3A%3AUtil%3A%3ATypeConstraints/json",
    "generated": "2026-06-16T10:22:02Z",
    "synopsis": "use Moose::Util::TypeConstraints;\nsubtype 'Natural',\nas 'Int',\nwhere { $ > 0 };\nsubtype 'NaturalLessThanTen',\nas 'Natural',\nwhere { $ < 10 },\nmessage { \"This number ($) is not less than ten!\" };\ncoerce 'Num',\nfrom 'Str',\nvia { 0+$ };\nclasstype 'DateTimeClass', { class => 'DateTime' };\nroletype 'Barks', { role => 'Some::Library::Role::Barks' };\nenum 'RGBColors', [qw(red green blue)];\nunion 'StringOrArray', [qw( String ArrayRef )];\nno Moose::Util::TypeConstraints;",
    "sections": {
        "NAME": {
            "content": "Moose::Util::TypeConstraints - Type constraint system for Moose\n",
            "subsections": []
        },
        "VERSION": {
            "content": "version 2.2200\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use Moose::Util::TypeConstraints;\n\nsubtype 'Natural',\nas 'Int',\nwhere { $ > 0 };\n\nsubtype 'NaturalLessThanTen',\nas 'Natural',\nwhere { $ < 10 },\nmessage { \"This number ($) is not less than ten!\" };\n\ncoerce 'Num',\nfrom 'Str',\nvia { 0+$ };\n\nclasstype 'DateTimeClass', { class => 'DateTime' };\n\nroletype 'Barks', { role => 'Some::Library::Role::Barks' };\n\nenum 'RGBColors', [qw(red green blue)];\n\nunion 'StringOrArray', [qw( String ArrayRef )];\n\nno Moose::Util::TypeConstraints;\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This module provides Moose with the ability to create custom type\nconstraints to be used in attribute definition.\n",
            "subsections": [
                {
                    "name": "Important Caveat",
                    "content": "This is NOT a type system for Perl 5. These are type constraints, and\nthey are not used by Moose unless you tell it to. No type inference is\nperformed, expressions are not typed, etc. etc. etc.\n\nA type constraint is at heart a small \"check if a value is valid\"\nfunction. A constraint can be associated with an attribute. This\nsimplifies parameter validation, and makes your code clearer to read,\nbecause you can refer to constraints by name.\n"
                },
                {
                    "name": "Slightly Less Important Caveat",
                    "content": "It is always a good idea to quote your type names.\n\nThis prevents Perl from trying to execute the call as an indirect object\ncall. This can be an issue when you have a subtype with the same name as\na valid class.\n\nFor instance:\n\nsubtype DateTime => as Object => where { $->isa('DateTime') };\n\nwill *just work*, while this:\n\nuse DateTime;\nsubtype DateTime => as Object => where { $->isa('DateTime') };\n\nwill fail silently and cause many headaches. The simple way to solve\nthis, as well as future proof your subtypes from classes which have yet\nto have been created, is to quote the type name:\n\nuse DateTime;\nsubtype 'DateTime', as 'Object', where { $->isa('DateTime') };\n"
                },
                {
                    "name": "Default Type Constraints",
                    "content": "This module also provides a simple hierarchy for Perl 5 types, here is\nthat hierarchy represented visually.\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\nNOTE: Any type followed by a type parameter \"[`a]\" can be parameterized,\nthis means you can say:\n\nArrayRef[Int]    # an array of integers\nHashRef[CodeRef] # a hash of str to CODE ref mappings\nScalarRef[Int]   # a reference to an integer\nMaybe[Str]       # value may be a string, may be undefined\n\nIf Moose finds a name in brackets that it does not recognize as an\nexisting type, it assumes that this is a class name, for example\n\"ArrayRef[DateTime]\".\n\nNOTE: Unless you parameterize a type, then it is invalid to include the\nsquare brackets. I.e. \"ArrayRef[]\" will be treated as a new type name,\n*not* as a parameterization of \"ArrayRef\".\n\nNOTE: The \"Undef\" type constraint for the most part works correctly now,\nbut edge cases may still exist, please use it sparingly.\n\nNOTE: The \"ClassName\" type constraint does a complex package existence\ncheck. This means that your class must be loaded for this type\nconstraint to pass.\n\nNOTE: The \"RoleName\" constraint checks a string is a *package name*\nwhich is a role, like 'MyApp::Role::Comparable'.\n"
                },
                {
                    "name": "Type Constraint Naming",
                    "content": "Type names declared via this module can only contain alphanumeric\ncharacters, colons (:), and periods (.).\n\nSince the types created by this module are global, it is suggested that\nyou namespace your types just as you would namespace your modules. So\ninstead of creating a *Color* type for your My::Graphics module, you\nwould call the type *My::Graphics::Types::Color* instead.\n"
                },
                {
                    "name": "Use with Other Constraint Modules",
                    "content": "This module can play nicely with other constraint modules with some\nslight tweaking. The \"where\" clause in types is expected to be a \"CODE\"\nreference which checks its first argument and returns a boolean. Since\nmost constraint modules work in a similar way, it should be simple to\nadapt them to work with Moose.\n\nFor instance, this is how you could use it with\nDeclare::Constraints::Simple to declare a completely new type.\n\ntype 'HashOfArrayOfObjects',\nwhere {\nIsHashRef(\n-keys   => HasLength,\n-values => IsArrayRef(IsObject)\n)->(@);\n};\n\nFor more examples see the t/examples/examplewDCS.t test file.\n\nHere is an example of using Test::Deep and its non-test related\n\"eqdeeply\" function.\n\ntype 'ArrayOfHashOfBarsAndRandomNumbers',\nwhere {\neqdeeply($,\narrayeach(subhashof({\nbar           => isa('Bar'),\nrandomnumber => ignore()\n})))\n};\n\nFor a complete example see the t/examples/examplewTestDeep.t test\nfile.\n"
                },
                {
                    "name": "Error messages",
                    "content": "Type constraints can also specify custom error messages, for when they\nfail to validate. This is provided as just another coderef, which\nreceives the invalid value in $, as in:\n\nsubtype 'PositiveInt',\nas 'Int',\nwhere { $ > 0 },\nmessage { \"$ is not a positive integer!\" };\n\nIf no message is specified, a default message will be used, which\nindicates which type constraint was being used and what value failed. If\nDevel::PartialDump (version 0.14 or higher) is installed, it will be\nused to display the invalid value, otherwise it will just be printed as\nis.\n"
                }
            ]
        },
        "FUNCTIONS": {
            "content": "",
            "subsections": [
                {
                    "name": "Type Constraint Constructors",
                    "content": "The following functions are used to create type constraints. They will\nalso register the type constraints your create in a global registry that\nis used to look types up by name.\n\nSee the \"SYNOPSIS\" for an example of how to use these.\n\nsubtype 'Name', as 'Parent', where { } ...\nThis creates a named subtype.\n\nIf you provide a parent that Moose does not recognize, it will\nautomatically create a new class type constraint for this name.\n\nWhen creating a named type, the \"subtype\" function should either be\ncalled with the sugar helpers (\"where\", \"message\", etc), or with a name\nand a hashref of parameters:\n\nsubtype( 'Foo', { where => ..., message => ... } );\n\nThe valid hashref keys are \"as\" (the parent), \"where\", \"message\", and\n\"inlineas\".\n\nsubtype as 'Parent', where { } ...\nThis creates an unnamed subtype and will return the type constraint\nmeta-object, which will be an instance of Moose::Meta::TypeConstraint.\n\nWhen creating an anonymous type, the \"subtype\" function should either be\ncalled with the sugar helpers (\"where\", \"message\", etc), or with just a\nhashref of parameters:\n\nsubtype( { where => ..., message => ... } );\n\nclasstype ($class, ?$options)\nCreates a new subtype of \"Object\" with the name $class and the metaclass\nMoose::Meta::TypeConstraint::Class.\n\n# Create a type called 'Box' which tests for objects which ->isa('Box')\nclasstype 'Box';\n\nBy default, the name of the type and the name of the class are the same,\nbut you can specify both separately.\n\n# Create a type called 'Box' which tests for objects which ->isa('ObjectLibrary::Box');\nclasstype 'Box', { class => 'ObjectLibrary::Box' };\n\nroletype ($role, ?$options)\nCreates a \"Role\" type constraint with the name $role and the metaclass\nMoose::Meta::TypeConstraint::Role.\n\n# Create a type called 'Walks' which tests for objects which ->does('Walks')\nroletype 'Walks';\n\nBy default, the name of the type and the name of the role are the same,\nbut you can specify both separately.\n\n# Create a type called 'Walks' which tests for objects which ->does('MooseX::Role::Walks');\nroletype 'Walks', { role => 'MooseX::Role::Walks' };\n\nmaybetype ($type)\nCreates a type constraint for either \"undef\" or something of the given\ntype.\n\nducktype ($name, \\@methods)\nThis will create a subtype of Object and test to make sure the value\n\"can()\" do the methods in \"\\@methods\".\n\nThis is intended as an easy way to accept non-Moose objects that provide\na certain interface. If you're using Moose classes, we recommend that\nyou use a \"requires\"-only Role instead.\n\nducktype (\\@methods)\nIf passed an ARRAY reference as the only parameter instead of the $name,\n\"\\@methods\" pair, this will create an unnamed duck type. This can be\nused in an attribute definition like so:\n\nhas 'cache' => (\nis  => 'ro',\nisa => ducktype( [qw( getset )] ),\n);\n\nenum ($name, \\@values)\nThis will create a basic subtype for a given set of strings. The\nresulting constraint will be a subtype of \"Str\" and will match any of\nthe items in \"\\@values\". It is case sensitive. See the \"SYNOPSIS\" for a\nsimple example.\n\nNOTE: This is not a true proper enum type, it is simply a convenient\nconstraint builder.\n\nenum (\\@values)\nIf passed an ARRAY reference as the only parameter instead of the $name,\n\"\\@values\" pair, this will create an unnamed enum. This can then be used\nin an attribute definition like so:\n\nhas 'sortorder' => (\nis  => 'ro',\nisa => enum([qw[ ascending descending ]]),\n);\n\nunion ($name, \\@constraints)\nThis will create a basic subtype where any of the provided constraints\nmay match in order to satisfy this constraint.\n\nunion (\\@constraints)\nIf passed an ARRAY reference as the only parameter instead of the $name,\n\"\\@constraints\" pair, this will create an unnamed union. This can then\nbe used in an attribute definition like so:\n\nhas 'items' => (\nis => 'ro',\nisa => union([qw[ Str ArrayRef ]]),\n);\n\nThis is similar to the existing string union:\n\nisa => 'Str|ArrayRef'\n\nexcept that it supports anonymous elements as child constraints:\n\nhas 'color' => (\nisa => 'ro',\nisa => union([ 'Int',  enum([qw[ red green blue ]]) ]),\n);\n\nas 'Parent'\nThis is just sugar for the type constraint construction syntax.\n\nIt takes a single argument, which is the name of a parent type.\n\nwhere { ... }\nThis is just sugar for the type constraint construction syntax.\n\nIt takes a subroutine reference as an argument. When the type constraint\nis tested, the reference is run with the value to be tested in $. This\nreference should return true or false to indicate whether or not the\nconstraint check passed.\n\nmessage { ... }\nThis is just sugar for the type constraint construction syntax.\n\nIt takes a subroutine reference as an argument. When the type constraint\nfails, then the code block is run with the value provided in $. This\nreference should return a string, which will be used in the text of the\nexception thrown.\n\ninlineas { ... }\nThis can be used to define a \"hand optimized\" inlinable version of your\ntype constraint.\n\nYou provide a subroutine which will be called *as a method* on a\nMoose::Meta::TypeConstraint object. It will receive a single parameter,\nthe name of the variable to check, typically something like \"$\" or\n\"$[0]\".\n\nThe subroutine should return a code string suitable for inlining. You\ncan assume that the check will be wrapped in parentheses when it is\ninlined.\n\nThe inlined code should include any checks that your type's parent types\ndo. If your parent type constraint defines its own inlining, you can\nsimply use that to avoid repeating code. For example, here is the\ninlining code for the \"Value\" type, which is a subtype of \"Defined\":\n\nsub {\n$[0]->parent()->inlinecheck($[1])\n. ' && !ref(' . $[1] . ')'\n}\n\ntype 'Name', where { } ...\nThis creates a base type, which has no parent.\n\nThe \"type\" function should either be called with the sugar helpers\n(\"where\", \"message\", etc), or with a name and a hashref of parameters:\n\ntype( 'Foo', { where => ..., message => ... } );\n\nThe valid hashref keys are \"where\", \"message\", and \"inlinedas\".\n"
                },
                {
                    "name": "Type Constraint Utilities",
                    "content": "matchontype $value => ( $type => \\&action, ... ?\\&default )\nThis is a utility function for doing simple type based dispatching\nsimilar to match/case in OCaml and case/of in Haskell. It is not as\nfeatureful as those languages, nor does not it support any kind of\nautomatic destructuring bind. Here is a simple Perl pretty printer\ndispatching over the core Moose types.\n\nsub ppprint {\nmy $x = shift;\nmatchontype $x => (\nHashRef => sub {\nmy $hash = shift;\n'{ '\n. (\njoin \", \" => map { $ . ' => ' . ppprint( $hash->{$} ) }\nsort keys %$hash\n) . ' }';\n},\nArrayRef => sub {\nmy $array = shift;\n'[ ' . ( join \", \" => map { ppprint($) } @$array ) . ' ]';\n},\nCodeRef   => sub {'sub { ... }'},\nRegexpRef => sub { 'qr/' . $ . '/' },\nGlobRef   => sub { '*' . B::svref2object($)->NAME },\nObject    => sub { $->can('tostring') ? $->tostring : $ },\nScalarRef => sub { '\\\\' . ppprint( ${$} ) },\nNum       => sub {$},\nStr       => sub { '\"' . $ . '\"' },\nUndef     => sub {'undef'},\n=> sub { die \"I don't know what $ is\" }\n);\n}\n\nOr a simple JSON serializer:\n\nsub tojson {\nmy $x = shift;\nmatchontype $x => (\nHashRef => sub {\nmy $hash = shift;\n'{ '\n. (\njoin \", \" =>\nmap { '\"' . $ . '\" : ' . tojson( $hash->{$} ) }\nsort keys %$hash\n) . ' }';\n},\nArrayRef => sub {\nmy $array = shift;\n'[ ' . ( join \", \" => map { tojson($) } @$array ) . ' ]';\n},\nNum   => sub {$},\nStr   => sub { '\"' . $ . '\"' },\nUndef => sub {'null'},\n=> sub { die \"$ is not acceptable json type\" }\n);\n}\n\nThe matcher is done by mapping a $type to an \"\\&action\". The $type can\nbe either a string type or a Moose::Meta::TypeConstraint object, and\n\"\\&action\" is a subroutine reference. This function will dispatch on the\nfirst match for $value. It is possible to have a catch-all by providing\nan additional subroutine reference as the final argument to\n\"matchontype\".\n"
                },
                {
                    "name": "Type Coercion Constructors",
                    "content": "You can define coercions for type constraints, which allow you to\nautomatically transform values to something valid for the type\nconstraint. If you ask your accessor to coerce by adding the option\n\"coerce => 1\", then Moose will run the type-coercion code first,\nfollowed by the type constraint check. This feature should be used\ncarefully as it is very powerful and could easily take off a limb if you\nare not careful.\n\nSee the \"SYNOPSIS\" for an example of how to use these.\n\ncoerce 'Name', from 'OtherName', via { ... }\nThis defines a coercion from one type to another. The \"Name\" argument is\nthe type you are coercing *to*.\n\nTo define multiple coercions, supply more sets of from/via pairs:\n\ncoerce 'Name',\nfrom 'OtherName', via { ... },\nfrom 'ThirdName', via { ... };\n\nfrom 'OtherName'\nThis is just sugar for the type coercion construction syntax.\n\nIt takes a single type name (or type object), which is the type being\ncoerced *from*.\n\nvia { ... }\nThis is just sugar for the type coercion construction syntax.\n\nIt takes a subroutine reference. This reference will be called with the\nvalue to be coerced in $. It is expected to return a new value of the\nproper type for the coercion.\n"
                },
                {
                    "name": "Creating and Finding Type Constraints",
                    "content": "These are additional functions for creating and finding type\nconstraints. Most of these functions are not available for importing.\nThe ones that are importable as specified.\n\nfindtypeconstraint($typename)\nThis function can be used to locate the Moose::Meta::TypeConstraint\nobject for a named type.\n\nThis function is importable.\n\nregistertypeconstraint($typeobject)\nThis function will register a Moose::Meta::TypeConstraint with the\nglobal type registry.\n\nThis function is importable.\n\nnormalizetypeconstraintname($typeconstraintname)\nThis method takes a type constraint name and returns the normalized\nform. This removes any whitespace in the string.\n\ncreatetypeconstraintunion($pipeseparatedtypes | @typeconstraintnames)\ncreatenamedtypeconstraintunion($name, $pipeseparatedtypes | @typeconstraintnames)\nThis can take a union type specification like 'Int|ArrayRef[Int]', or a\nlist of names. It returns a new Moose::Meta::TypeConstraint::Union\nobject.\n\ncreateparameterizedtypeconstraint($typename)\nGiven a $typename in the form of 'BaseType[ContainerType]', this will\ncreate a new Moose::Meta::TypeConstraint::Parameterized object. The\n\"BaseType\" must already exist as a parameterizable type.\n\ncreateclasstypeconstraint($class, $options)\nGiven a class name this function will create a new\nMoose::Meta::TypeConstraint::Class object for that class name.\n\nThe $options is a hash reference that will be passed to the\nMoose::Meta::TypeConstraint::Class constructor (as a hash).\n\ncreateroletypeconstraint($role, $options)\nGiven a role name this function will create a new\nMoose::Meta::TypeConstraint::Role object for that role name.\n\nThe $options is a hash reference that will be passed to the\nMoose::Meta::TypeConstraint::Role constructor (as a hash).\n\ncreateenumtypeconstraint($name, $values)\nGiven a enum name this function will create a new\nMoose::Meta::TypeConstraint::Enum object for that enum name.\n\ncreateducktypeconstraint($name, $methods)\nGiven a duck type name this function will create a new\nMoose::Meta::TypeConstraint::DuckType object for that enum name.\n\nfindorparsetypeconstraint($typename)\nGiven a type name, this first attempts to find a matching constraint in\nthe global registry.\n\nIf the type name is a union or parameterized type, it will create a new\nobject of the appropriate, but if given a \"regular\" type that does not\nyet exist, it simply returns false.\n\nWhen given a union or parameterized type, the member or base type must\nalready exist.\n\nIf it creates a new union or parameterized type, it will add it to the\nglobal registry.\n\nfindorcreateisatypeconstraint($typename)\nfindorcreatedoestypeconstraint($typename)\nThese functions will first call \"findorparsetypeconstraint\". If that\nfunction does not return a type, a new type object will be created.\n\nThe \"isa\" variant will use \"createclasstypeconstraint\" and the \"does\"\nvariant will use \"createroletypeconstraint\".\n\ngettypeconstraintregistry\nReturns the Moose::Meta::TypeConstraint::Registry object which keeps\ntrack of all type constraints.\n\nlistalltypeconstraints\nThis will return a list of type constraint names in the global registry.\nYou can then fetch the actual type object using\n\"findtypeconstraint($typename)\".\n\nlistallbuiltintypeconstraints\nThis will return a list of builtin type constraints, meaning those which\nare defined in this module. See the \"Default Type Constraints\" section\nfor a complete list.\n\nexporttypeconstraintsasfunctions\nThis will export all the current type constraints as functions into the\ncaller's namespace (\"Int()\", \"Str()\", etc). Right now, this is mostly\nused for testing, but it might prove useful to others.\n\ngetallparameterizabletypes\nThis returns all the parameterizable types that have been registered, as\na list of type objects.\n\naddparameterizabletype($type)\nAdds $type to the list of parameterizable types\n"
                }
            ]
        },
        "BUGS": {
            "content": "See \"BUGS\" in Moose for details on reporting bugs.\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\nthe same terms as the Perl 5 programming language system itself.\n",
            "subsections": []
        }
    },
    "summary": "Moose::Util::TypeConstraints - Type constraint system for Moose",
    "flags": [],
    "examples": [],
    "see_also": []
}