Type::Utils(3) | User Contributed Perl Documentation | Type::Utils(3) |
Type::Utils - utility functions to make defining and using type constraints a little easier
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($_) };
This module is covered by the Type-Tiny stability policy.
This module provides utility functions to make defining and using type constraints a little easier.
Many of the following are similar to the similarly named functions described in Moose::Util::TypeConstraints.
declare EvenInt, as Int, where { $_ % 2 == 0 }; my $EvenInt = declare as Int, where { $_ % 2 == 0 };
NOTE: If the caller package inherits from Type::Library then any non-anonymous types declared in the package will be automatically installed into the library.
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.
Actually, you should use "declare" instead; this is just an alias.
This function is not exported by default.
Actually, you should use "declare" instead; this is just an alias.
This function is not exported by default.
declare EvenInt, as Int, where { $_ % 2 == 0 };
declare EvenInt, as Int, where { $_ % 2 == 0 };
The coderef operates on $_, which is the value being tested.
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.
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)"); };
If $package is omitted, is 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.
If $package is omitted, is 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.
Many of the following are similar to the similarly named functions described in Moose::Util::TypeConstraints.
coerce EvenInt, from Int, via { $_ * 2 }; # As a coderef... coerce EvenInt, from Int, q { $_ * 2 }; # or as a string!
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.
Coercions declared this way are immutable (frozen).
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.
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.
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.
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.
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
Note that, for example, "42" satisfies Int, but it would satisfy the type constraints Num, Str, and Any as well. In this case, the classifier has picked the most specific type constraint that "42" satisfies.
If no type constraint is satisfied by the value, then the classifier will return undef.
It uses the syntax of Type::Parser. Firstly the Type::Registry for the caller package is consulted; if that doesn't have a match, Types::Standard is consulted for standard type constraint names.
If none of the above yields a type constraint, and the caller class is a Moose-based class, then "dwim_type" attempts to look the type constraint up in the Moose type registry. If it's a Mouse-based class, then the Mouse type registry is used instead.
If no type constraint can be found via these normal methods, several fallbacks are available:
You can alter which should be attempted, and in which 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, by default the fallbacks attempted are:
lookup_via_moose, lookup_via_mouse, make_class_type
You may set "fallback" to an empty arrayref to avoid using any of these fallbacks.
You can specify an alternative for the caller using the "for" option.
my $type = dwim_type("ArrayRef", for => "Moose::Object");
While it's probably better overall to use the proper Type::Registry interface for resolving type constraint strings, this function often does what you want.
It should never die if it fails to find a type constraint (but may die if the type constraint string is syntactically malformed), preferring to return undef.
This function is not exported by default.
This function is not exported by default. This function is not even exported by "use Type::Utils -all". You must request it explicitly.
use Type::Utils "is";
Beware using this in test scripts because it has the same name as a function exported by Test::More. Note that you can rename this function if "is" will cause conflicts:
use Type::Utils "is" => { -as => "isntnt" };
This function is not exported by default, but it is exported by "use Type::Utils -all".
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.
By default, all of the functions documented above are exported, except "subtype" and "type" (prefer "declare" instead), "extends", "dwim_type", "match_on_type"/"compile_match_on_type", "classifier", and "english_list".
This module uses Exporter::Tiny; see the documentation of that module for tips and tricks importing from Type::Utils.
Please report any bugs to <http://rt.cpan.org/Dist/Display.html?Queue=Type-Tiny>.
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.
Toby Inkster <tobyink@cpan.org>.
This software is copyright (c) 2013-2014, 2017-2020 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.
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.
2020-10-28 | perl v5.34.0 |