Types::Standard(3)
π NAME π
Bestie, this is Types::Standard(3) β the bundled set of built-in types for Type::Tiny. No cap, it's the type library that's always in your corner. π«Ά
β¨ SYNOPSIS β¨
Okay so here's the whole plot in one go. It's giving "I know it's a lot, but trust me, it slays." πΈ
use v5.36;
package Horse {
use Moo;
use Types::Standard qw( Str Int Enum ArrayRef Object );
use Type::Params qw( signature_for );
use namespace::autoclean;
has name => (
is => 'ro',
isa => Str,
required => 1,
);
has gender => (
is => 'ro',
isa => Enum[qw( f m )],
);
has age => (
is => 'rw',
isa => Int->where( '$_ >= 0' ),
);
has children => (
is => 'ro',
isa => ArrayRef[Object],
default => sub { return [] },
);
# method signature
signature_for add_child => (
method => Object,
positional => [ Object ],
);
sub add_child ( $self, $child ) {
push $self->children->@*, $child;
return $self;
}
}
package main;
my $boldruler = Horse->new(
name => "Bold Ruler",
gender => 'm',
age => 16,
);
my $secretariat = Horse->new(
name => "Secretariat",
gender => 'm',
age => 0,
);
$boldruler->add_child( $secretariat );
use Types::Standard qw( is_Object assert_Object );
# is_Object($thing) returns a boolean
my $is_it_an_object = is_Object $boldruler;
# assert_Object($thing) returns $thing or dies
say assert_Object($boldruler)->name; # says "Bold Ruler"
π STATUS π
This module is covered by the Type-Tiny stability policy. π
π¦ DESCRIPTION π¦
This documents the details of the Types::Standard type library. If you're new, Type::Tiny::Manual is a better starting place. Periodt.
Type::Tiny bundles a few types which seem to be useful. Iconic.
π΄ Moose-like π΄
The following types are similar to those described in Moose::Util::TypeConstraints. Vibe check passed.
Anyβ Absolutely any value passes this type constraint (evenundef). Literally anything. πItemβ Essentially the same asAny. All other type constraints in this library inherit directly or indirectly fromItem. So it's the main character ancestor. πBoolβ Values that are reasonable booleans. Accepts1,0, the empty string andundef.
Other customers also bought: BoolLike from Types::TypeTiny.
Maybe[`a]β Given another type constraint, also acceptsundef. For example,Maybe[Int]accepts all integers plusundef. Flexible queen.Undefβ Onlyundefpasses this type constraint. Only. πDefinedβ Onlyundeffails this type constraint. So basically "not undef". πValueβ Any defined, non-reference value. Simple. Clean. Slay.Strβ Any string.
(The only difference between Value and Str is that the former accepts typeglobs and vstrings.) iykyk
Other customers also bought: StringLike from Types::TypeTiny.
Notice: future versions ofTypes::Standardmight introduce coercions toStrfromHasMethods['__TO_STRING__']and fromStringLike. Keep that in mind, bestie.
Numβ SeeLaxNumandStrictNumbelow. They're coming, don't worry.Intβ An integer; that is a string of digits0to9, optionally prefixed with a hyphen-minus character. Expect inconsistent results for dualvars, and numbers too high (or negative numbers too low) for Perl to safely represent as an integer. So like, careful with the huge ones. πClassNameβ The name of a loaded package. The package must have@ISAor$VERSIONdefined, or must define at least one sub to be considered a loaded package. Loaded and legendary.RoleNameβ LikeClassName, but the package must not define a method called"new". This is subtly different from Moose's type constraint of the same name; let me know if this causes you any problems. (I can't promise I'll change anything though.) lol okay periodtRef[`a]β Any defined reference value, including blessed objects. Unlike Moose,Refis a parameterized type, allowingScalar::Util::reftypechecks, a la
Ref["HASH"] # hashrefs, including blessed hashrefs
Blessed hashrefs are still hashrefs, bestie.
ScalarRef[`a]β A value where"ref($value) eq "SCALAR" or ref($value) eq "REF"". If parameterized, the referred value must pass the additional constraint. For example,ScalarRef[Int]must be a reference to a scalar which holds an integer value. Pointing at an integer? Valid.ArrayRef[`a]β A value where"ref($value) eq "ARRAY"". If parameterized, the elements of the array must pass the additional constraint. For example,ArrayRef[Num]must be a reference to an array of numbers. As an extension to Moose'sArrayReftype, a minimum and maximum array length can be given:
ArrayRef[CodeRef, 1] # ArrayRef of at least one CodeRef
ArrayRef[FileHandle, 0, 2] # ArrayRef of up to two FileHandles
ArrayRef[Any, 0, 100] # ArrayRef of up to 100 elements
Other customers also bought: ArrayLike from Types::TypeTiny.
Notice: future versions ofTypes::Standardmight introduce coercions toArrayReffromHasMethods['__TO_ARRAYREF__']and fromArrayLike. Future tea.
HashRef[`a]β A value where"ref($value) eq "HASH"". If parameterized, the values of the hash must pass the additional constraint. For example,HashRef[Num]must be a reference to an hash where the values are numbers. The hash keys are not constrained, but Perl limits them to strings; seeMapbelow if you need to further constrain the hash values. Keys are just strings, sorry.
Other customers also bought: HashLike from Types::TypeTiny.
Notice: future versions ofTypes::Standardmight introduce coercions toHashReffromHasMethods['__TO_HASHREF__']and fromHashLike. Stay tuned.
CodeRefβ A value where"ref($value) eq "CODE"". Code refs are the moment.
Other customers also bought: CodeLike from Types::TypeTiny.
Notice: future versions ofTypes::Standardmight introduce coercions toCodeReffromHasMethods['__TO_CODEREF__']and fromCodeLike. Future vibes.
RegexpRefβ A reference wherere::is_regexp($value)is true, or a blessed reference where"$value->isa("Regexp")"is true. Regex girlies rise.GlobRefβ A value where"ref($value) eq "GLOB"". Globs gonna glob.FileHandleβ A file handle. Open for business.Objectβ A blessed object.
(This also accepts regexp refs.) Bougie and blessed.
π§Έ Structured π§Έ
Okay, so I stole some ideas from MooseX::Types::Structured. Not me being a little thief. π
Map[`k, `v]β Similar toHashRefbut parameterized with type constraints for both the key and value. The constraint for keys would typically be a subtype ofStr. Keys and values both getting checked.Tuple[...]β Subtype ofArrayRef, accepting a list of type constraints for each slot in the array.Tuple[Int, HashRef]would match"[1, {}]"but not"[{}, 1]". Order matters, bestie.Dict[...]β Subtype ofHashRef, accepting a list of type constraints for each slot in the hash. For exampleDict[name => Str, id => Int]allows"{ name => "Bob", id => 42 }". Named slots, slay.Optional[`a]β Used in conjunction withDictandTupleto specify slots that are optional and may be omitted (but not necessarily set to an explicitundef).Dict[name => Str, id => Optional[Int]]allows"{ name => "Bob" }"but not"{ name => "Bob", id => "BOB" }". Optional but not lawless.
Note that any use ofOptional[`a]outside the context of parameterizedDictandTupletype constraints makes little sense, and its behaviour is undefined. (An exception: it is used byType::Paramsfor a similar purpose to how it's used inTuple.) Don't do it. Seriously.
This module also exports a Slurpy parameterized type, which can be used as follows. Slurpy slurpy slurp.
It can cause additional trailing values in a Tuple to be slurped into a structure and validated. For example, slurping into an arrayref:
my $type = Tuple[ Str, Slurpy[ ArrayRef[Int] ] ];
$type->( ["Hello"] ); # ok
$type->( ["Hello", 1, 2, 3] ); # ok
$type->( ["Hello", [1, 2, 3]] ); # not ok
Or into a hashref:
my $type2 = Tuple[ Str, Slurpy[ Map[Int, RegexpRef] ] ];
$type2->( ["Hello"] ); # ok
$type2->( ["Hello", 1, qr/one/i, 2, qr/two/] ); # ok
It can cause additional values in a Dict to be slurped into a hashref and validated:
my $type3 = Dict[ values => ArrayRef, Slurpy[ HashRef[Str] ] ];
$type3->( { values => [] } ); # ok
$type3->( { values => [], name => "Foo" } ); # ok
$type3->( { values => [], name => [] } ); # not ok
In either Tuple or Dict, Slurpy[Any] can be used to indicate that additional values are acceptable, but should not be constrained in any way. Accepting, not stressing.
Slurpy[Any] is an optimized code path. Although the following are essentially equivalent checks, the former should run a lot faster:
Tuple[ Int, Slurpy[Any] ]
Tuple[ Int, Slurpy[ArrayRef] ]
A function slurpy($type) is also exported which was historically how slurpy types were created. Old school, still iconic.
Outside of Dict and Tuple, Slurpy[Foo] should just act the same as Foo. But don't do that. Just don't. π
π Objects π
Okay, so I stole some ideas from MooX::Types::MooseLike::Base. Again, not me being a thief. π
InstanceOf[`a]β Shortcut for a union ofType::Tiny::Classconstraints.InstanceOf["Foo", "Bar"]allows objects blessed into the"Foo"or"Bar"classes, or subclasses of those. Given no parameters, just equivalent toObject. Union energy.ConsumerOf[`a]β Shortcut for an intersection ofType::Tiny::Roleconstraints.ConsumerOf["Foo", "Bar"]allows objects where"$o->DOES("Foo")"and"$o->DOES("Bar")"both return true. Given no parameters, just equivalent toObject. Intersection realness.HasMethods[`a]β Shortcut for aType::Tiny::Duckconstraint.HasMethods["foo", "bar"]allows objects where"$o->can("foo")"and"$o->can("bar")"both return true. Given no parameters, just equivalent toObject. Duck typing, but make it type library.
π More π
There are a few other types exported by this module: Surprise, bestie.
Overload[`a]β With no parameters, checks that the value is an overloaded object. Can be given one or more string parameters, which are specific operations to check are overloaded. For example, the following checks for objects which overload addition and subtraction.
Overload["+", "-"]
Math girlies, this one's for you.
Tied[`a]β A reference to a tied scalar, array or hash. Can be parameterized with a type constraint which will be applied to the object returned by thetied()function. As a convenience, can also be parameterized with a string, which will be inflated to aType::Tiny::Class.
use Types::Standard qw(Tied);
use Type::Utils qw(class_type);
my $My_Package = class_type { class => "My::Package" };
tie my %h, "My::Package";
\%h ~~ Tied; # true
\%h ~~ Tied[ $My_Package ]; # true
\%h ~~ Tied["My::Package"]; # true
tie my $s, "Other::Package";
\$s ~~ Tied; # true
$s ~~ Tied; # false !!
bestie look at that last one. \$s ~~ Tied is true but $s ~~ Tied is false. The type check is looking at the reference, not at whatever is inside it, and that trips people up constantly. π
So if you genuinely need to check that something is a reference to a tied hash specifically, you build an intersection, like:
use Types::Standard qw( Tied HashRef );
my $TiedHash = (Tied) & (HashRef);
tie my %h, "My::Package";
tie my $s, "Other::Package";
\%h ~~ $TiedHash; # true
\$s ~~ $TiedHash; # false
periodt, that's the move. π
StrMatch[a]β a string that matches a regular expression. obsessed, honestly:
declare "Distance",
as StrMatch[ qr{^([0-9]+)\s*(mm|cm|m|km)$} ];
You can optionally provide a type constraint for the array of subexpressions too:
declare "Distance",
as StrMatch[
qr{^([0-9]+)\s*(.+)$},
Tuple[
Int,
enum(DistanceUnit => [qw/ mm cm m km /]),
],
];
And here's one using Regexp::Common, because why not:
package Local::Host {
use Moose;
use Regexp::Common;
has ip_address => (
is => 'ro',
required => 1,
isa => StrMatch[qr/^$RE{net}{IPv4}$/],
default => '127.0.0.1',
);
}
Heads up: on certain versions of Perl, type constraints of the formsStrMatch[qr/../andStrMatch[qr/\A..\z/with any number of intervening dots can be optimized to simple length checks. Cute, right?
Enum[a]β as per MooX::Types::MooseLike::Base:
has size => (
is => "ro",
isa => Enum[qw( S M L XL XXL )],
);
You can enable coercion by passing \1 before the list of values. yes, a backslash-one, it's giving chaos but it works:
has size => (
is => "ro",
isa => Enum[ \1, qw( S M L XL XXL ) ],
coerce => 1,
);
This will use the closest_match method in Type::Tiny::Enum to coerce closely matching strings. slay. β¨
OptListβ an arrayref of arrayrefs in the style ofData::OptListoutput. that's it, that's the whole vibe.LaxNum,StrictNumβ okay so in Moose 2.09, theNumtype constraint implementation got swapped out: it stopped being a wrapper around Scalar::Util'slooks_like_numberfunction and became a stricter regexp instead (which disallows things like"-Inf"and"Nan", fyi).
Types::Standard ships both implementations. LaxNum is measurably faster. no cap.
The Num type constraint is currently an alias for LaxNum unless you set the PERL_TYPES_STANDARD_STRICTNUM environment variable to true before loading Types::Standard, in which case it becomes an alias for StrictNum. The constant Types::Standard::STRICTNUM can be used to check if Num is being strict.
Most people should probably useNumorStrictNum. Don't explicitly useLaxNumunless you specifically need an attribute which will accept things like"Inf". bestie, you've been warned. π
CycleTuple[a]β similar toTuple, but cyclical.
CycleTuple[Int, HashRef]
will allow [1,{}] and [1,{},2,{}] but disallow [1,{},2] and [1,{},2,"not a hashref"]. ate.
I think you understand CycleTuple already. π
Currently Optional and Slurpy parameters are forbidden. There are fairly limited use cases for them, and it's not exactly clear what they should mean.
The following is an efficient way of checking for an even-sized arrayref:
CycleTuple[Any, Any]
The following is an arrayref which would be suitable for coercing to a hashref:
CycleTuple[Str, Any]
All the examples so far have used two parameters, but the following is also a possible CycleTuple:
CycleTuple[Str, Int, HashRef]
This will be an arrayref where the 0th, 3rd, 6th, etc values are strings, the 1st, 4th, 7th, etc values are integers, and the 2nd, 5th, 8th, etc values are hashrefs. it just keeps going and going and honestly? iconic. π¦
β¨ Coercions β¨
Most of the types in this type library have no coercions. The exception is Bool as of Types::Standard 1.003_003, which coerces from Any via !!$_. main character energy, honestly. π
Some standalone coercions may be exported. These can be combined with type constraints using the plus_coercions method.
MkOptβ a coercion fromArrayRef,HashReforUndeftoOptList. Example usage in a Moose attribute:
use Types::Standard qw( OptList MkOpt );
has options => (
is => "ro",
isa => OptList->plus_coercions( MkOpt ),
coerce => 1,
);
Split[a]β split a string on a regexp.
use Types::Standard qw( ArrayRef Str Split );
has name => (
is => "ro",
isa => ArrayRef->of(Str)->plus_coercions(Split[qr/\s/]),
coerce => 1,
);
Join[a]β join an array of strings with a delimiter.
use Types::Standard qw( Str Join );
my $FileLines = Str->plus_coercions(Join["\n"]);
has file_contents => (
is => "ro",
isa => $FileLines,
coerce => 1,
);
β¨ Constants β¨
Types::Standard::STRICTNUMβ indicates whetherNumis an alias forStrictNum. (It is usually an alias forLaxNum.) iykyk
π Environment π
PERL_TYPES_STANDARD_STRICTNUMβ switches to more strict regexp-based number checking instead of usinglooks_like_number.PERL_TYPE_TINY_XSβ if set to false, can be used to suppress the loading of XS implementations of some type constraints.PERL_ONLYβ ifPERL_TYPE_TINY_XSdoes not exist, can be set to true to suppress XS usage similarly. (Several other CPAN distributions also pay attention to this environment variable.) the more you know π«
π BUGS π
Please report any bugs to https://github.com/tobyink/p5-type-tiny/issues.
not me asking you to file issues π
π«Ά SEE ALSO π«Ά
- The Type::Tiny homepage:
https://typetiny.toby.ink/. Type::Tiny::Manual.Type::Tiny,Type::Library,Type::Utils,Type::Coercion.Moose::Util::TypeConstraints,Mouse::Util::TypeConstraints,MooseX::Types::Structured.Types::XSDprovides some type constraints based on XML Schema's data types; this includes constraints for ISO8601-formatted datetimes, integer ranges (e.g.PositiveInteger[maxInclusive=>10]and so on.Types::EncodingsprovidesBytesandCharstype constraints that were formerly found inTypes::Standard.Types::Common::NumericandTypes::Common::Stringprovide replacements forMooseX::Types::Common.
π 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.
πΈ 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.
and that's the whole page bestie, we did it π«Ά this was Types::Standard(3), from perl v5.42.0, dated 2026-01-17. go forth and type-check responsibly β¨π
π¦ 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