man > Moose::Util::TypeConstraints

📛 NAME

Moose::Util::TypeConstraints - Type constraint system for Moose

🚀 Quick Reference

Use CaseCommandDescription
Create a named subtypesubtype 'Natural', as 'Int', where { $_ > 0 };🔍 Define a new type constraint that inherits from a parent type with a validation check
Create a subtype with custom error messagesubtype 'PositiveInt', as 'Int', where { $_ > 0 }, message { "$_ is not positive!" };💬 Add a custom error message when validation fails
Define a coercioncoerce 'Num', from 'Str', via { 0+$_ };🔄 Automatically convert from one type to another
Create a class type constraintclass_type 'DateTimeClass', { class => 'DateTime' };🏷️ Constrain to objects of a specific class (or subclass)
Create a role type constraintrole_type 'Barks', { role => 'Some::Role' };🎭 Constrain to objects that do a specific role
Create an enum typeenum 'RGBColors', [qw(red green blue)];🌈 Constrain to a fixed set of string values
Create a union typeunion 'StringOrArray', [qw( String ArrayRef )];🔗 Constrain to any of the listed types
Create an anonymous subtypesubtype as 'Parent', where { ... };🔒 Use inline without registering a global name
Create a duck typeduck_type 'Name', [qw( method1 method2 )];🦆 Constrain to objects that can do certain methods
Type dispatchmatch_on_type $value => ( HashRef => sub { ... }, => sub { default } );🎯 Simple type-based dispatch similar to match/case

📖 VERSION

version 2.2200

📝 SYNOPSIS

use Moose::Util::TypeConstraints;

subtype 'Natural',
    as 'Int',
    where { $_ > 0 };

subtype 'NaturalLessThanTen',
    as 'Natural',
    where { $_ < 10 },
    message { "This number ($_) is not less than ten!" };

coerce 'Num',
    from 'Str',
    via { 0+$_ };

class_type 'DateTimeClass', { class => 'DateTime' };

role_type 'Barks', { role => 'Some::Library::Role::Barks' };

enum 'RGBColors', [qw(red green blue)];

union 'StringOrArray', [qw( String ArrayRef )];

no Moose::Util::TypeConstraints;

📚 DESCRIPTION

This module provides Moose with the ability to create custom type constraints to be used in attribute definition.

⚠️ Important Caveat

This is NOT a type system for Perl 5. These are type constraints, and they are not used by Moose unless you tell it to. No type inference is performed, expressions are not typed, etc. etc. etc.

A type constraint is at heart a small "check if a value is valid" function. A constraint can be associated with an attribute. This simplifies parameter validation, and makes your code clearer to read, because you can refer to constraints by name.

🔶 Slightly Less Important Caveat

It is always a good idea to quote your type names.

This prevents Perl from trying to execute the call as an indirect object call. This can be an issue when you have a subtype with the same name as a valid class.

For instance:

subtype DateTime => as Object => where { $_->isa('DateTime') };

will just work, while this:

use DateTime;
subtype DateTime => as Object => where { $_->isa('DateTime') };

will fail silently and cause many headaches. The simple way to solve this, as well as future proof your subtypes from classes which have yet to have been created, is to quote the type name:

use DateTime;
subtype 'DateTime', as 'Object', where { $_->isa('DateTime') };

🔢 Default Type Constraints

This module also provides a simple hierarchy for Perl 5 types, here is that hierarchy represented visually.

Any
    Item
        Bool
        Maybe[`a]
        Undef
        Defined
            Value
                Str
                    Num
                        Int
                    ClassName
                    RoleName
            Ref
                ScalarRef[`a]
                ArrayRef[`a]
                HashRef[`a]
                CodeRef
                RegexpRef
                GlobRef
                FileHandle
                Object

NOTE: Any type followed by a type parameter "[`a]" can be parameterized, this means you can say:

ArrayRef[Int]    # an array of integers
HashRef[CodeRef] # a hash of str to CODE ref mappings
ScalarRef[Int]   # a reference to an integer
Maybe[Str]       # value may be a string, may be undefined

If Moose finds a name in brackets that it does not recognize as an existing type, it assumes that this is a class name, for example "ArrayRef[DateTime]".

NOTE: Unless you parameterize a type, then it is invalid to include the square brackets. I.e. "ArrayRef[]" will be treated as a new type name, not as a parameterization of "ArrayRef".

NOTE: The "Undef" type constraint for the most part works correctly now, but edge cases may still exist, please use it sparingly.

NOTE: The "ClassName" type constraint does a complex package existence check. This means that your class must be loaded for this type constraint to pass.

NOTE: The "RoleName" constraint checks a string is a package name which is a role, like 'MyApp::Role::Comparable'.

🏷️ Type Constraint Naming

Type names declared via this module can only contain alphanumeric characters, colons (:), and periods (.).

Since the types created by this module are global, it is suggested that you namespace your types just as you would namespace your modules. So instead of creating a Color type for your My::Graphics module, you would call the type My::Graphics::Types::Color instead.

🔗 Use with Other Constraint Modules

This module can play nicely with other constraint modules with some slight tweaking. The "where" clause in types is expected to be a "CODE" reference which checks its first argument and returns a boolean. Since most constraint modules work in a similar way, it should be simple to adapt them to work with Moose.

For instance, this is how you could use it with Declare::Constraints::Simple to declare a completely new type.

type 'HashOfArrayOfObjects',
    where {
        IsHashRef(
            -keys   => HasLength,
            -values => IsArrayRef(IsObject)
        )->(@_);
    };

For more examples see the t/examples/example_w_DCS.t test file.

Here is an example of using Test::Deep and its non-test related "eq_deeply" function.

type 'ArrayOfHashOfBarsAndRandomNumbers',
    where {
        eq_deeply($_,
            array_each(subhashof({
                bar           => isa('Bar'),
                random_number => ignore()
            })))
      };

For a complete example see the t/examples/example_w_TestDeep.t test file.

💬 Error messages

Type constraints can also specify custom error messages, for when they fail to validate. This is provided as just another coderef, which receives the invalid value in $_, as in:

subtype 'PositiveInt',
     as 'Int',
     where { $_ > 0 },
     message { "$_ is not a positive integer!" };

If no message is specified, a default message will be used, which indicates which type constraint was being used and what value failed. If Devel::PartialDump (version 0.14 or higher) is installed, it will be used to display the invalid value, otherwise it will just be printed as is.

🔧 FUNCTIONS

🏗️ Type Constraint Constructors

The following functions are used to create type constraints. They will also register the type constraints your create in a global registry that is used to look types up by name.

See the "SYNOPSIS" for an example of how to use these.

🧰 Type Constraint Utilities

🔄 Type Coercion Constructors

You can define coercions for type constraints, which allow you to automatically transform values to something valid for the type constraint. If you ask your accessor to coerce by adding the option "coerce => 1", then Moose will run the type-coercion code first, followed by the type constraint check. This feature should be used carefully as it is very powerful and could easily take off a limb if you are not careful.

See the "SYNOPSIS" for an example of how to use these.

🔍 Creating and Finding Type Constraints

These are additional functions for creating and finding type constraints. Most of these functions are not available for importing. The ones that are importable as specified.

🐛 BUGS

See "BUGS" in Moose for details on reporting bugs.

👥 AUTHORS

📄 COPYRIGHT AND LICENSE

This software is copyright (c) 2006 by Infinity Interactive, Inc.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.

perl v5.34.0 2022-02-06 Moose::Util::TypeConstraints(3pm)

Moose::Util::TypeConstraints
📛 NAME 🚀 Quick Reference 📖 VERSION 📝 SYNOPSIS 📚 DESCRIPTION
⚠️ Important Caveat 🔶 Slightly Less Important Caveat 🔢 Default Type Constraints 🏷️ Type Constraint Naming 🔗 Use with Other Constraint Modules 💬 Error messages
🔧 FUNCTIONS
🏗️ Type Constraint Constructors 🧰 Type Constraint Utilities 🔄 Type Coercion Constructors 🔍 Creating and Finding Type Constraints
🐛 BUGS 👥 AUTHORS 📄 COPYRIGHT AND LICENSE

Generated by phpman v4.9.26-1-g511901d · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-07-28 07:18 @216.73.217.46
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Valid XHTML 1.0 Transitional!Valid CSS!
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format

^_top_^