Moose::...traints(3)

Moose::Util::TypeConstraints πŸ’– (the type constraint system for Moose)

okay bestie so this page lives in the Perl docs as Moose::Util::TypeConstraints, and it's literally the whole vibe of "is this value even valid tho" for Moose. buckle up, it's a long one, but we're getting through it together 🫢


VERSION

version 2.4000 ✨


SYNOPSIS

look at her. iconic. the way she just does all of this:

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;

that's the whole menu, no cap πŸ’…


DESCRIPTION

so this module hands Moose the power to make custom type constraints that you can then use when you're defining attributes. that's it, that's the job πŸ’–

Important Caveat 🚨

okay so let's get one thing STRAIGHT, bestie: this is NOT a type system for Perl 5. these are type constraints, and Moose does not use them unless you literally tell it to. there's no type inference, expressions don't get typed, none of that. etc etc etc. she said what she said 😌

a type constraint is, at its heart, just a tiny little "is this value valid or not" function. you can attach a constraint to an attribute, and boom β€” parameter validation got simpler AND your code reads way clearer because you get to refer to constraints by name. slay.

Slightly Less Important Caveat 🌸

bestie. quote your type names. always. fr fr.

why? because quoting stops Perl from trying to run the call as an indirect object call. this becomes A Whole Situation when you've got a subtype with the same name as a real, valid class.

like, check this out:

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

this one? just works. but this one:

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

...will fail silently and cause you many, many headaches 😭 the easy fix β€” and honestly the future-proofing move so your subtypes survive classes that haven't even been written yet β€” is to just quote the name:

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

periodt. quote your names. πŸŽ€

Default Type Constraints πŸ‘‘

this module also comes with a little hierarchy for Perl 5 types. here's that hierarchy, 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 that's followed by a type parameter like [a]` can be parameterized! meaning you can say stuff like:

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

and if Moose sees a name in brackets that it doesn't recognize as an existing type, it just assumes it's a class name β€” like ArrayRef[DateTime]. easy.

NOTE: if you don't parameterize a type, then putting square brackets on it is invalid. so ArrayRef[] gets treated as a brand new type name, not as a parameterization of ArrayRef. don't do that πŸ™ˆ

NOTE: the Undef type constraint mostly works correctly now, but edge cases may still exist β€” please use it sparingly.

NOTE: the ClassName type constraint does a complex package existence check, which means your class has to be loaded for this constraint to pass. no loading, no pass. iykyk.

NOTE: the RoleName constraint checks that a string is a package name that's a role, like 'MyApp::Role::Comparable'.

Type Constraint Naming ✨

type names declared through this module can only contain:

  • alphanumeric characters
  • colons (:)
  • periods (.)

and since the types this module makes are global, you should namespace your types the exact same way you'd namespace your modules. so instead of making a Color type for your My::Graphics module, you'd call it My::Graphics::Types::Color. do it. it's the polite thing 🫢

Use with Other Constraint Modules 🌈

good news bestie, this module can play nicely with other constraint modules if you tweak things just a lil bit. the where clause in types expects to be a CODE reference that checks its first argument and returns a boolean. and since most constraint modules work kinda the same way, adapting them for Moose is pretty simple.

for instance, here's how you could use it with Declare::Constraints::Simple to declare a completely new type:

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

want more examples? go peek at the t/examples/example_w_DCS.t test file πŸ’–

and here's an example 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, check out 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! you just hand it another coderef, and that coderef receives the invalid value in $_, like so:

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

if you don't specify a message, a default one gets used β€” it tells you which type constraint was in play and what value flopped. and if Devel::PartialDump (version 0.14 or higher) is installed, it'll be used to show off the invalid value; otherwise it just gets printed as-is. cute πŸ’…


FUNCTIONS πŸ”₯

Type Constraint Constructors πŸŽ€

these functions below are what you use to create type constraints. they'll also register the constraints you create in a global registry that Moose uses to look types up by name. head back to the "SYNOPSIS" for an example of how to use 'em πŸ’–

  • subtype 'Name', as 'Parent', where { } ... β€” this one creates a named subtype. if you give it a parent that Moose doesn't recognize, it'll automatically make a new class type constraint for that name. when you're creating a named type, subtype should either be called with the sugar helpers (where, message, etc), or with a name plus a hashref of parameters:
subtype( 'Foo', { where => ..., message => ... } );

the valid hashref keys are as (that's the parent), where, message, and inline_as. πŸ’–

  • subtype as 'Parent', where { } ... β€” this one creates an unnamed subtype and returns the type constraint meta-object, which is an instance of Moose::Meta::TypeConstraint. when you're creating an anonymous type, subtype 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 if you want:

# 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. simple as πŸ¦‹
  • duck_type ($name, \@methods) β€” this creates a subtype of Object and tests to make sure the value can() do the methods in \@methods. it's meant as an easy way to accept non-Moose objects that provide a certain interface. and if you're using Moose classes? we recommend you use a requires-only Role instead πŸ’œ
  • duck_type (\@methods) β€” if you pass an ARRAY reference as the only parameter instead of the $name, \@methods pair, this creates an unnamed duck type. you can use it in an attribute definition like so:
has 'cache' => (
    is  => 'ro',
    isa => duck_type( [qw( get_set )] ),
);
  • enum ($name, \@values) β€” this creates 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. check the "SYNOPSIS" for a simple example.
NOTE: this is not a true proper enum type β€” it's just a convenient constraint builder. πŸ’€
  • enum (\@values) β€” if you pass an ARRAY reference as the only parameter instead of the $name, \@values pair, this creates an unnamed enum. then you can use it in an attribute definition like so:
has 'sort_order' => (
    is  => 'ro',
    isa => enum([qw[ ascending descending ]]),
);
  • union ($name, \@constraints) β€” this creates a basic subtype where any of the provided constraints may match in order to satisfy this constraint.
  • union (\@constraints) β€” if you pass an ARRAY reference as the only parameter instead of the $name, \@constraints pair, this creates an unnamed union. then you can use it 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 β€” and this is the glow-up β€” 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. periodt.

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. so if it fails, you get a custom lil message, cute!

inline_as { ... }

This can be used to define a "hand optimized" inlinable version of your type constraint. fancy, right?

You provide a subroutine which will be called as a method 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".

✨ Type Constraint Utilities ✨

match_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. (we keep the original typo energy, iykyk) 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". so you can have a default case, slay!

πŸ’– 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. ⚠️ seriously, bestie, be careful with this one.

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.

πŸ¦‹ 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.

  • 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

πŸ› BUGS πŸ›

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

πŸ‘‘ AUTHORS πŸ‘‘

  • Stevan Little <stevan@cpan.org>
  • Dave Rolsky <autarch@urth.org>
  • Jesse Luehrs <doy@cpan.org>
  • Shawn M Moore <sartak@cpan.org>
  • Χ™Χ•Χ‘Χœ Χ§Χ•Χ’'מן (Yuval Kogman) <nothingmuch@woobling.org>
  • Karen Etheridge <ether@cpan.org>
  • Florian Ragwitz <rafl@debian.org>
  • Hans Dieter Pearcey <hdp@cpan.org>
  • Chris Prather <chris@prather.org>
  • Matt S Trout <mstrout@cpan.org>

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.


and that's a wrap, bestie! this page is from perl v5.42.0, dated 2025-07-25, and it's Moose::...traints(3). slay! πŸ’…βœ¨

πŸ“¦ where this page comes from