Type::Utils(3)
π Type::Utils π
okay bestie, welcome to Type::Utils β the manual page is Type::Utils(3), a User Contributed Perl Documentation page, and it's literally the utility belt for making type constraints a little easier to define and use. no cap. π«Ά
β¨ SYNOPSIS β¨
package Types::Mine;
use Type::Library -base;
use Type::Utils -all;
BEGIN { extends "Types::Standard" };
declare "AllCaps",
as "Str",
where { uc($_) eq $_ },
inline_as { my $varname = $_[1]; "uc($varname) eq $varname" };
coerce "AllCaps",
from "Str", via { uc($_) };
π STATUS π
This module is covered by the Type-Tiny stability policy. it's official, it's vetted, it's giving stable. π
π¦ DESCRIPTION π¦
This module hands you utility functions so that defining and using type constraints is a little easier. that's the whole vibe. πΈ
π Type declaration functions π
A lot of these are similar to the similarly named functions described in Moose::Util::TypeConstraints. (iykyk.)
declare $name, %optionsdeclare %options
Declare a named or anonymous type constraint. use as and where to specify the parent type (if any) and (possibly) refine its definition.
declare EvenInt, as Int, where { $_ % 2 == 0 };
my $EvenInt = declare as Int, where { $_ % 2 == 0 };
NOTE: named types get automatically added to the caller's type registry. (seeType::Registry.) and if the caller package inherits fromType::Library, named types are also automatically installed into the library and made available as exports. slay. π
Hidden gem: if you're inheriting from a type constraint that includes some coercions, you can include coercion => 1 in the %options hash to inherit the coercions. lowkey iconic. π
subtype $name, %optionssubtype %options
Declare a named or anonymous type constraint which is descended from an existing type constraint. use as and where to specify the parent type and refine its definition.
Actuallyβ¦ you should use declare instead; this is just an alias. π
This function is not exported by default.
type $name, %optionstype %options
Declare a named or anonymous type constraint which is not descended from an existing type constraint. use where to provide a coderef that constrains values.
Also: you should use declare instead; this is just an alias too. π
This function is not exported by default.
as $parentβ used withdeclareto specify a parent type constraint:
declare EvenInt, as Int, where { $_ % 2 == 0 };
where { BLOCK }β used withdeclareto provide the constraint coderef:
declare EvenInt, as Int, where { $_ % 2 == 0 };
The coderef operates on $_, which is the value being tested. yes, the classic $_. π
message { BLOCK }β generate a custom error message when a value fails validation:
declare EvenInt,
as Int,
where { $_ % 2 == 0 },
message {
Int->validate($_) or "$_ is not divisible by two";
};
Without a custom message, the messages generated by Type::Tiny are along the lines of Value "33" did not pass type constraint "EvenInt", which is usually reasonable. fr fr. π
inline_as { BLOCK }β generate a string of Perl code that can be used to inline the type check into other functions. if your type check is being used within a Moose or Moo constructor or accessor methods, or used byType::Params, this can lead to significant performance improvements. β‘
declare EvenInt,
as Int,
where { $_ % 2 == 0 },
inline_as {
my ($constraint, $varname) = @_;
my $perlcode =
$constraint->parent->inline_check($varname)
. "&& ($varname % 2 == 0)";
return $perlcode;
};
warn EvenInt->inline_check('$xxx'); # demonstration
Your inline_as block can return a list, in which case these will be smushed together with &&. the first item on the list may be undef, in which case the undef will be replaced by the inlined parent type constraint. (and will throw an exception if there is no parent.) π
declare EvenInt,
as Int,
where { $_ % 2 == 0 },
inline_as {
return (undef, "($_ % 2 == 0)");
};
class_type $name, { class => $package, %options }class_type { class => $package, %options }class_type $name
Shortcut for declaring a Type::Tiny::Class type constraint. π«
If $package is omitted, it's assumed to be the same as $name. if $name contains "::" (which would be an invalid name as far as Type::Tiny is concerned), this will be removed.
So for example, class_type("Foo::Bar") declares a Type::Tiny::Class type constraint named "FooBar" which constrains values to objects blessed into the "Foo::Bar" package. cute.
role_type $name, { role => $package, %options }role_type { role => $package, %options }role_type $name
Shortcut for declaring a Type::Tiny::Role type constraint. π
If $package is omitted, it's assumed to be the same as $name. if $name contains "::" (which would be an invalid name as far as Type::Tiny is concerned), this will be removed.
duck_type $name, \@methodsduck_type \@methods
Shortcut for declaring a Type::Tiny::Duck type constraint. π¦ if it walks like a duck etc.
union $name, \@constraintsunion \@constraints
Shortcut for declaring a Type::Tiny::Union type constraint. π€
enum $name, \@valuesenum \@values
Shortcut for declaring a Type::Tiny::Enum type constraint. π
intersection $name, \@constraintsintersection \@constraints
Shortcut for declaring a Type::Tiny::Intersection type constraint. π«
π Coercion declaration functions π
Many of the following are similar to the similarly named functions described in Moose::Util::TypeConstraints. (yes, again. it's a whole genre.)
coerce $target, @coercionsβ add coercions to the target type constraint. the list of coercions is a list of type constraint, conversion code pairs. conversion code can be either a string of Perl code or a coderef; in either case the value to be converted is$_. πfrom $sourceβ sugar to specify a type constraint in a list of coercions:
coerce EvenInt, from Int, via { $_ * 2 }; # As a coderef...
coerce EvenInt, from Int, q { $_ * 2 }; # or as a string!
via { BLOCK }β sugar to specify a coderef in a list of coercions.declare_coercion $name, \%opts, $type1, $code1, ...declare_coercion \%opts, $type1, $code1, ...
Declares a coercion that is not explicitly attached to any type in the library. for example:
declare_coercion "ArrayRefFromAny", from "Any", via { [$_] };
This coercion will be exportable from the library as a Type::Coercion object, but the ArrayRef type exported by the library won't automatically use it. it's doing its own thing, main character energy. β¨
Coercions declared this way are immutable (frozen). π§
to_type $typeβ used withdeclare_coercionto declare the target type constraint for a coercion, but still without explicitly attaching the coercion to the type constraint:
declare_coercion "ArrayRefFromAny",
to_type "ArrayRef",
from "Any", via { [$_] };
You should pretty much always use this when declaring an unattached coercion, because it's exceedingly useful for a type coercion to know what it will coerce to β this allows it to skip coercion when no coercion is needed (e.g. avoiding coercing [] to [ [] ]) and allows assert_coerce to work properly. π«Ά
π Type library management π
extends @librariesβ indicates that this type library extends other type libraries, importing their type constraints. π
Should usually be executed in a BEGIN block.
This is not exported by default because it's not fun to export it to Moo, Moose or Mouse classes! use Type::Utils -all can be used to import it into your type library. π
πΈ Other πΈ
match_on_type $value => ($type => \&action, ..., \&default?)
Something like a switch/case or given/when construct. it dispatches along different code paths depending on the type of the incoming value. example blatantly stolen from the Moose documentation:
sub to_json
{
my $value = shift;
return match_on_type $value => (
HashRef() => sub {
my $hash = shift;
'{ '
. (
join ", " =>
map { '"' . $_ . '" : ' . to_json( $hash->{$_} ) }
sort keys %$hash
) . ' }';
},
ArrayRef() => sub {
my $array = shift;
'[ '.( join ", " => map { to_json($_) } @$array ).' ]';
},
Num() => q {$_},
Str() => q { '"' . $_ . '"' },
Undef() => q {'null'},
=> sub { die "$_ is not acceptable json type" },
);
}
Note that unlike Moose, code can be specified as a string instead of a coderef. (e.g. for Num, Str and Undef above.) π
For improved performance, try compile_match_on_type.
This function is not exported by default.
my $coderef = compile_match_on_type($type => \&action, ..., \&default?)
Compile a match_on_type block into a coderef. the following JSON converter is about two orders of magnitude faster than the previous example:
sub to_json;
*to_json = compile_match_on_type(
HashRef() => sub {
my $hash = shift;
'{ '
. (
join ", " =>
map { '"' . $_ . '" : ' . to_json( $hash->{$_} ) }
sort keys %$hash
) . ' }';
},
ArrayRef() => sub {
my $array = shift;
'[ '.( join ", " => map { to_json($_) } @$array ).' ]';
},
Num() => q {$_},
Str() => q { '"' . $_ . '"' },
Undef() => q {'null'},
=> sub { die "$_ is not acceptable json type" },
);
Remember to store the coderef somewhere fairly permanent so that you don't compile it over and over. state variables (in Perl >= 5.10) are good for this. (same sort of idea as Type::Params.) π₯
This function is not exported by default.
my $coderef = classifier(@types)
Returns a coderef that can be used to classify values according to their type constraint. the coderef, when passed a value, returns a type constraint which the value satisfies. π§
β¨ part 1 done bestie, more is coming β¨
use feature qw( say );
use Type::Utils qw( classifier );
use Types::Standard qw( Int Num Str Any );
my $classifier = classifier(Str, Int, Num, Any);
say $classifier->( "42" )->name; # Int
say $classifier->( "4.2" )->name; # Num
say $classifier->( [] )->name; # Any
okay so notice how "42" satisfies Int but bestie it also satisfies Num, Str and Any?? yeah. multiple vibes. in that case the classifier just picks the most specific type constraint that "42" satisfies. it's giving main character energy among type constraints. π
and if no type constraint is satisfied by the value at all? the classifier returns undef. tragic but honest. π
π dwim_type($string, %options) π
give it a string like ArrayRef[Int|CodeRef] and it turns it into a type constraint object, hopefully doing what you meant. fingers crossed bestie π«Ά
it uses the syntax of Type::Parser. first up, the Type::Registry for the caller package gets consulted; if that's a no-match, Types::Standard gets asked about standard type constraint names. two-step vibe check. β¨
if neither of those yields a type constraint, and the caller class is Moose-based, then dwim_type tries to look it up in the Moose type registry. if it's Mouse-based instead, the Mouse type registry gets used. slay.
and if nothing at all can be found through those normal methods, there's a whole fallback squad available:
lookup_via_mooseβ look it up in the Moose registry even if the caller is a non-Moose class.lookup_via_mouseβ look it up in the Mouse registry even if the caller is a non-Mouse class.make_class_typeβ create a brand new Type::Tiny::Class constraint.make_role_typeβ create a brand new Type::Tiny::Role constraint.
you can change which ones get attempted, and in what order, by passing an option to dwim_type:
my $type = Type::Utils::dwim_type(
"ArrayRef[Int]",
fallback => [ "lookup_via_mouse" , "make_role_type" ],
);
for historical reasons π the fallbacks attempted by default are:
lookup_via_moose, lookup_via_mouse, make_class_type
and if you want zero fallbacks you can just set fallback to an empty arrayref. no notes, just boundaries. π
you can also specify an alternative caller using the for option:
my $type = dwim_type("ArrayRef", for => "Moose::Object");
ngl it's probably better overall to use the proper Type::Registry interface for resolving type constraint strings, but this function often does what you want. it's the low-effort bestie of type resolution. π¦
it should never die if it fails to find a type constraint (though it may die if the type constraint string is syntactically malformed), preferring to return undef instead. graceful queen. β¨
this function is not exported by default. don't forget to ask for it!
πΈ is($type, $value) πΈ
a shortcut for $type->check($value) β but plot twist, if $type is a string it'll get looked up via dwim_type first. convenient β¨
this function is not exported by default. it's not even exported by use Type::Utils -all. you have to request it explicitly:
use Type::Utils "is";
β οΈ beware using this in test scripts bestie, because it has the same name as a function exported by Test::More. collision city. π
good news: you can rename this function if is is gonna cause conflicts:
use Type::Utils "is" => { -as => "isntnt" };
π assert($type, $value) π
like is but instead of returning a boolean it returns $value, and dies if the value fails the type check. no chill, all commitment. π
this function is not exported by default, but it is exported by use Type::Utils -all. okay so it's on the list. π
π english_list(\$conjunction, @items) π
joins the items with commas, placing a conjunction before the final item. the conjunction is optional and defaults to "and". grammar queen behaviour. π
english_list(qw/foo bar baz/); # "foo, bar, and baz"
english_list(\"or", qw/quux quuux/); # "quux or quuux"
this function is not exported by default.
π¦ EXPORT π¦
by default, all of the functions documented above are exported β except:
subtypeandtype(preferdeclareinstead, bestie, it's the glow-up β¨)extendsdwim_typematch_on_type/compile_match_on_typeclassifierenglish_list
this module uses Exporter::Tiny; go read that module's documentation for tips and tricks on importing from Type::Utils. iykyk π«Ά
π BUGS π
please report any bugs to <https://github.com/tobyink/p5-type-tiny/issues>. not me asking you to file an issueβ¦ actually yes, me asking. do it bestie π
π SEE ALSO π
- Type::Tiny::Manual.
- Type::Tiny, Type::Library, Types::Standard, Type::Coercion.
- Type::Tiny::Class, Type::Tiny::Role, Type::Tiny::Duck, Type::Tiny::Enum, Type::Tiny::Union.
- Moose::Util::TypeConstraints, Mouse::Util::TypeConstraints.
βοΈ AUTHOR βοΈ
Toby Inkster <tobyink@cpan.org>. π
π COPYRIGHT AND LICENCE π
this software is copyright (c) 2013-2014, 2017-2025 by Toby Inkster.
this is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. periodt. π
π¨ DISCLAIMER OF WARRANTIES π¨
THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
read that one twice bestie, it's the all caps one for a reason π
and that's the whole page!! π this was perl v5.42.0, dated 2026-01-17, and it's the Type::Utils(3) manual page. go forth and constrain your types, you absolute icon π πβ¨
π¦ where this page comes from
- fedora 44: perl-Type-Tiny 2.010001-2.fc44 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms