Synopsis
use v5.12;
use strict;
use warnings;
package Horse {
use Moo;
use Types::Standard qw( Str Int Enum ArrayRef Object );
use Type::Params qw( compile );
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 [] },
);
sub add_child {
state $check = signature(
method => Object,
positional => [ Object ],
); # method signature
my ( $self, $child ) = $check->( @_ ); # unpack @_
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. Type::Tiny::Manual is a better starting place if you're new.
Type::Tiny bundles a few types which seem to be useful.
Moose-like
The following types are similar to those described in Moose::Util::TypeConstraints .
-
Any
Absolutely any value passes this type constraint (even undef).
-
Item
Essentially the same as Any . All other type constraints in this library inherit directly or indirectly from Item .
-
Bool
Values that are reasonable booleans. Accepts 1, 0, the empty string and undef.
Other customers also bought: BoolLike from Types::TypeTiny .
-
Maybe[`a]
Given another type constraint, also accepts undef. For example, Maybe[Int] accepts all integers plus undef.
-
Undef
Only undef passes this type constraint.
-
Defined
Only undef fails this type constraint.
-
Value
Any defined, non-reference value.
-
Str
Any string.
(The only difference between Value and Str is that the former accepts typeglobs and vstrings.)
Other customers also bought: StringLike from Types::TypeTiny .
-
Num
See LaxNum and StrictNum below.
-
Int
An integer; that is a string of digits 0 to 9, 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.
-
ClassName
The name of a loaded package. The package must have
@ISA
or$VERSION
defined, or must define at least one sub to be considered a loaded package. -
RoleName
Like ClassName , 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.) -
Ref[`a]
Any defined reference value, including blessed objects.
Unlike Moose, Ref is a parameterized type, allowing Scalar::Util::reftype checks, a la
Ref["HASH"] # hashrefs, including blessed hashrefs
-
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.
-
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's ArrayRef type, 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 .
-
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; see Map below if you need to further constrain the hash values.
Other customers also bought: HashLike from Types::TypeTiny .
-
CodeRef
A value where
ref($value) eq "CODE"
.Other customers also bought: CodeLike from Types::TypeTiny .
-
RegexpRef
A reference where
re::is_regexp($value)
is true, or a blessed reference where$value->isa("Regexp")
is true. -
GlobRef
A value where
ref($value) eq "GLOB"
. -
FileHandle
A file handle.
-
Object
A blessed object.
(This also accepts regexp refs.)
Structured
Okay, so I stole some ideas from MooseX::Types::Structured .
-
Map[`k, `v]
Similar to HashRef but parameterized with type constraints for both the key and value. The constraint for keys would typically be a subtype of Str .
-
Tuple[...]
Subtype of ArrayRef , accepting a list of type constraints for each slot in the array.
Tuple[Int, HashRef] would match
[1, {}]
but not[{}, 1]
. -
Dict[...]
Subtype of HashRef , accepting a list of type constraints for each slot in the hash.
For example Dict[name => Str, id => Int] allows
{ name => "Bob", id => 42 }
. -
Optional[`a]
Used in conjunction with Dict and Tuple to specify slots that are optional and may be omitted (but not necessarily set to an explicit undef).
Dict[name => Str, id => Optional[Int]] allows
{ name => "Bob" }
but not{ name => "Bob", id => "BOB" }
.Note that any use of Optional[`a] outside the context of parameterized Dict and Tuple type constraints makes little sense, and its behaviour is undefined. (An exception: it is used by Type::Params for a similar purpose to how it's used in Tuple .)
This module also exports a Slurpy parameterized type, which can be used as follows.
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.
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.
Outside of Dict and Tuple , Slurpy[Foo] should just act the same as Foo . But don't do that.
See Also
Type::Tiny , Type::Library , Type::Utils , Type::Coercion .
Moose::Util::TypeConstraints , Mouse::Util::TypeConstraints , MooseX::Types::Structured .
Types::XSD provides 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::Encodings provides Bytes and Chars type constraints that were formerly found in Types::Standard.
Types::Common::Numeric and Types::Common::String provide replacements for MooseX::Types::Common .