Moose::Util::TypeConstraints - Type constraint system for Moose
| Use Case | Command | Description |
|---|---|---|
| Create a named subtype | subtype '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 message | subtype 'PositiveInt', as 'Int', where { $_ > 0 }, message { "$_ is not positive!" }; | 💬 Add a custom error message when validation fails |
| Define a coercion | coerce 'Num', from 'Str', via { 0+$_ }; | 🔄 Automatically convert from one type to another |
| Create a class type constraint | class_type 'DateTimeClass', { class => 'DateTime' }; | 🏷️ Constrain to objects of a specific class (or subclass) |
| Create a role type constraint | role_type 'Barks', { role => 'Some::Role' }; | 🎭 Constrain to objects that do a specific role |
| Create an enum type | enum 'RGBColors', [qw(red green blue)]; | 🌈 Constrain to a fixed set of string values |
| Create a union type | union 'StringOrArray', [qw( String ArrayRef )]; | 🔗 Constrain to any of the listed types |
| Create an anonymous subtype | subtype as 'Parent', where { ... }; | 🔒 Use inline without registering a global name |
| Create a duck type | duck_type 'Name', [qw( method1 method2 )]; | 🦆 Constrain to objects that can do certain methods |
| Type dispatch | match_on_type $value => ( HashRef => sub { ... }, => sub { default } ); | 🎯 Simple type-based dispatch similar to match/case |
version 2.2200
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;
This module provides Moose with the ability to create custom type constraints to be used in attribute definition.
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.
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') };
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 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.
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.
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.
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.
subtype 'Name', as 'Parent', where { } ...subtype( 'Foo', { where => ..., message => ... } ); The valid hashref keys are "as" (the parent), "where", "message", and "inline_as".subtype as 'Parent', where { } ...subtype( { where => ..., message => ... } );class_type ($class, ?$options)# Create a type called 'Box' which tests for objects which ->isa('Box')
class_type 'Box';By default, the name of the type and the name of the class are the same, but you can specify both separately.# Create a type called 'Box' which tests for objects which ->isa('ObjectLibrary::Box');
class_type 'Box', { class => 'ObjectLibrary::Box' };role_type ($role, ?$options)# Create a type called 'Walks' which tests for objects which ->does('Walks')
role_type 'Walks';By default, the name of the type and the name of the role are the same, but you can specify both separately.# Create a type called 'Walks' which tests for objects which ->does('MooseX::Role::Walks');
role_type 'Walks', { role => 'MooseX::Role::Walks' };maybe_type ($type)duck_type ($name, \@methods)duck_type (\@methods)has 'cache' => (
is => 'ro',
isa => duck_type( [qw( get_set )] ),
);enum ($name, \@values)enum (\@values)has 'sort_order' => (
is => 'ro',
isa => enum([qw[ ascending descending ]]),
);union ($name, \@constraints)union (\@constraints)has 'items' => (
is => 'ro',
isa => union([qw[ Str ArrayRef ]]),
);This is similar to the existing string union:isa => 'Str|ArrayRef'except that it supports anonymous elements as child constraints:has 'color' => (
isa => 'ro',
isa => union([ 'Int', enum([qw[ red green blue ]]) ]),
);as 'Parent'where { ... }message { ... }inline_as { ... }sub {
$_[0]->parent()->_inline_check($_[1])
. ' && !ref(' . $_[1] . ')'
}type 'Name', where { } ...type( 'Foo', { where => ..., message => ... } ); The valid hashref keys are "where", "message", and "inlined_as".match_on_type $value => ( $type => \&action, ... ?\&default )sub ppprint {
my $x = shift;
match_on_type $x => (
HashRef => sub {
my $hash = shift;
'{ '
. (
join ", " => map { $_ . ' => ' . ppprint( $hash->{$_} ) }
sort keys %$hash
) . ' }';
},
ArrayRef => sub {
my $array = shift;
'[ ' . ( join ", " => map { ppprint($_) } @$array ) . ' ]';
},
CodeRef => sub {'sub { ... }'},
RegexpRef => sub { 'qr/' . $_ . '/' },
GlobRef => sub { '*' . B::svref_2object($_)->NAME },
Object => sub { $_->can('to_string') ? $_->to_string : $_ },
ScalarRef => sub { '\\' . ppprint( ${$_} ) },
Num => sub {$_},
Str => sub { '"' . $_ . '"' },
Undef => sub {'undef'},
=> sub { die "I don't know what $_ is" }
);
}Or a simple JSON serializer:sub to_json {
my $x = shift;
match_on_type $x => (
HashRef => sub {
my $hash = shift;
'{ '
. (
join ", " =>
map { '"' . $_ . '" : ' . to_json( $hash->{$_} ) }
sort keys %$hash
) . ' }';
},
ArrayRef => sub {
my $array = shift;
'[ ' . ( join ", " => map { to_json($_) } @$array ) . ' ]';
},
Num => sub {$_},
Str => sub { '"' . $_ . '"' },
Undef => sub {'null'},
=> sub { die "$_ is not acceptable json type" }
);
}The matcher is done by mapping a $type to an "\&action". The $type can be either a string type or a Moose::Meta::TypeConstraint object, and "\&action" is a subroutine reference. This function will dispatch on the first match for $value. It is possible to have a catch-all by providing an additional subroutine reference as the final argument to "match_on_type".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.
coerce 'Name', from 'OtherName', via { ... }coerce 'Name',
from 'OtherName', via { ... },
from 'ThirdName', via { ... };from 'OtherName'via { ... }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.
find_type_constraint($type_name)register_type_constraint($type_object)normalize_type_constraint_name($type_constraint_name)create_type_constraint_union($pipe_separated_types | @type_constraint_names)create_named_type_constraint_union($name, $pipe_separated_types | @type_constraint_names)create_parameterized_type_constraint($type_name)create_class_type_constraint($class, $options)create_role_type_constraint($role, $options)create_enum_type_constraint($name, $values)create_duck_type_constraint($name, $methods)find_or_parse_type_constraint($type_name)find_or_create_isa_type_constraint($type_name)find_or_create_does_type_constraint($type_name)get_type_constraint_registrylist_all_type_constraintslist_all_builtin_type_constraintsexport_type_constraints_as_functionsget_all_parameterizable_typesadd_parameterizable_type($type)See "BUGS" in Moose for details on reporting bugs.
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)
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)
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format