TypeConstraintConstructors
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{}...
This creates a named subtype.
If you provide a parent that Moose does not recognize, it will automatically create a new class type
constraint for this name.
When creating a named type, the "subtype" function should either be called with the sugar helpers
("where", "message", etc), or with a name and a hashref of parameters:
subtype( 'Foo', { where => ..., message => ... } );
The valid hashref keys are "as" (the parent), "where", "message", and "inline_as".
subtypeas'Parent',where{}...
This creates an unnamed subtype and will return the type constraint meta-object, which will be an
instance of Moose::Meta::TypeConstraint.
When creating an anonymous type, the "subtype" function should either be called with the sugar helpers
("where", "message", etc), or with just a hashref of parameters:
subtype( { where => ..., message => ... } );
class_type($class,?$options)
Creates a new subtype of "Object" with the name $class and the metaclass
Moose::Meta::TypeConstraint::Class.
# 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)
Creates a "Role" type constraint with the name $role and the metaclass Moose::Meta::TypeConstraint::Role.
# 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)
Creates a type constraint for either "undef" or something of the given type.
duck_type($name,\@methods)
This will create a subtype of Object and test to make sure the value can() do the methods in "\@methods".
This is intended as an easy way to accept non-Moose objects that provide a certain interface. If you're
using Moose classes, we recommend that you use a "requires"-only Role instead.
duck_type(\@methods)
If passed an ARRAY reference as the only parameter instead of the $name, "\@methods" pair, this will
create an unnamed duck type. This can be used in an attribute definition like so:
has 'cache' => (
is => 'ro',
isa => duck_type( [qw( get_set )] ),
);
enum($name,\@values)
This will create a basic subtype for a given set of strings. The resulting constraint will be a subtype
of "Str" and will match any of the items in "\@values". It is case sensitive. See the "SYNOPSIS" for a
simple example.
NOTE: This is not a true proper enum type, it is simply a convenient constraint builder.
enum(\@values)
If passed an ARRAY reference as the only parameter instead of the $name, "\@values" pair, this will
create an unnamed enum. This can then be used in an attribute definition like so:
has 'sort_order' => (
is => 'ro',
isa => enum([qw[ ascending descending ]]),
);
union($name,\@constraints)
This will create a basic subtype where any of the provided constraints may match in order to satisfy this
constraint.
union(\@constraints)
If passed an ARRAY reference as the only parameter instead of the $name, "\@constraints" pair, this will
create an unnamed union. This can then be used in an attribute definition like so:
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'
This is just sugar for the type constraint construction syntax.
It takes a single argument, which is the name of a parent type.
where{...}
This is just sugar for the type constraint construction syntax.
It takes a subroutine reference as an argument. When the type constraint is tested, the reference is run
with the value to be tested in $_. This reference should return true or false to indicate whether or not
the constraint check passed.
message{...}
This is just sugar for the type constraint construction syntax.
It takes a subroutine reference as an argument. When the type constraint fails, then the code block is
run with the value provided in $_. This reference should return a string, which will be used in the text
of the exception thrown.
inline_as{...}
This can be used to define a "hand optimized" inlinable version of your type constraint.
You provide a subroutine which will be called asamethod on a Moose::Meta::TypeConstraint object. It
will receive a single parameter, the name of the variable to check, typically something like "$_" or
"$_[0]".
The subroutine should return a code string suitable for inlining. You can assume that the check will be
wrapped in parentheses when it is inlined.
The inlined code should include any checks that your type's parent types do. If your parent type
constraint defines its own inlining, you can simply use that to avoid repeating code. For example, here
is the inlining code for the "Value" type, which is a subtype of "Defined":
sub {
$_[0]->parent()->_inline_check($_[1])
. ' && !ref(' . $_[1] . ')'
}
type'Name',where{}...
This creates a base type, which has no parent.
The "type" function should either be called with the sugar helpers ("where", "message", etc), or with a
name and a hashref of parameters:
type( 'Foo', { where => ..., message => ... } );
The valid hashref keys are "where", "message", and "inlined_as".
TypeConstraintUtilitiesmatch_on_type$value=>($type=>\&action,...?\&default)
This is a utility function for doing simple type based dispatching similar to match/case in OCaml and
case/of in Haskell. It is not as featureful as those languages, nor does not it support any kind of
automatic destructuring bind. Here is a simple Perl pretty printer dispatching over the core Moose types.
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".
TypeCoercionConstructors
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{...}
This defines a coercion from one type to another. The "Name" argument is the type you are coercing to.
To define multiple coercions, supply more sets of from/via pairs:
coerce 'Name',
from 'OtherName', via { ... },
from 'ThirdName', via { ... };
from'OtherName'
This is just sugar for the type coercion construction syntax.
It takes a single type name (or type object), which is the type being coerced from.
via{...}
This is just sugar for the type coercion construction syntax.
It takes a subroutine reference. This reference will be called with the value to be coerced in $_. It is
expected to return a new value of the proper type for the coercion.
CreatingandFindingTypeConstraints
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)
This function can be used to locate the Moose::Meta::TypeConstraint object for a named type.
This function is importable.
register_type_constraint($type_object)
This function will register a Moose::Meta::TypeConstraint with the global type registry.
This function is importable.
normalize_type_constraint_name($type_constraint_name)
This method takes a type constraint name and returns the normalized form. This removes any whitespace in
the string.
create_type_constraint_union($pipe_separated_types|@type_constraint_names)create_named_type_constraint_union($name,$pipe_separated_types|@type_constraint_names)
This can take a union type specification like 'Int|ArrayRef[Int]', or a list of names. It returns a new
Moose::Meta::TypeConstraint::Union object.
create_parameterized_type_constraint($type_name)
Given a $type_name in the form of 'BaseType[ContainerType]', this will create a new
Moose::Meta::TypeConstraint::Parameterized object. The "BaseType" must already exist as a parameterizable
type.
create_class_type_constraint($class,$options)
Given a class name this function will create a new Moose::Meta::TypeConstraint::Class object for that
class name.
The $options is a hash reference that will be passed to the Moose::Meta::TypeConstraint::Class
constructor (as a hash).
create_role_type_constraint($role,$options)
Given a role name this function will create a new Moose::Meta::TypeConstraint::Role object for that role
name.
The $options is a hash reference that will be passed to the Moose::Meta::TypeConstraint::Role constructor
(as a hash).
create_enum_type_constraint($name,$values)
Given a enum name this function will create a new Moose::Meta::TypeConstraint::Enum object for that enum
name.
create_duck_type_constraint($name,$methods)
Given a duck type name this function will create a new Moose::Meta::TypeConstraint::DuckType object for
that enum name.
find_or_parse_type_constraint($type_name)
Given a type name, this first attempts to find a matching constraint in the global registry.
If the type name is a union or parameterized type, it will create a new object of the appropriate, but if
given a "regular" type that does not yet exist, it simply returns false.
When given a union or parameterized type, the member or base type must already exist.
If it creates a new union or parameterized type, it will add it to the global registry.
find_or_create_isa_type_constraint($type_name)find_or_create_does_type_constraint($type_name)
These functions will first call "find_or_parse_type_constraint". If that function does not return a type,
a new type object will be created.
The "isa" variant will use "create_class_type_constraint" and the "does" variant will use
"create_role_type_constraint".
get_type_constraint_registry
Returns the Moose::Meta::TypeConstraint::Registry object which keeps track of all type constraints.
list_all_type_constraints
This will return a list of type constraint names in the global registry. You can then fetch the actual
type object using find_type_constraint($type_name).
list_all_builtin_type_constraints
This will return a list of builtin type constraints, meaning those which are defined in this module. See
the "Default Type Constraints" section for a complete list.
export_type_constraints_as_functions
This will export all the current type constraints as functions into the caller's namespace (Int(), Str(),
etc). Right now, this is mostly used for testing, but it might prove useful to others.
get_all_parameterizable_types
This returns all the parameterizable types that have been registered, as a list of type objects.
add_parameterizable_type($type)
Adds $type to the list of parameterizable types