.\" -*- mode: troff; coding: utf-8 -*- .\" Automatically generated by Pod::Man 5.0102 (Pod::Simple 3.45) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>. .ie n \{\ . ds C` "" . ds C' "" 'br\} .el\{\ . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Type::Tiny::Manual::UsingWithMoo 3" .TH Type::Tiny::Manual::UsingWithMoo 3 2024-09-01 "perl v5.40.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH NAME Type::Tiny::Manual::UsingWithMoo \- basic use of Type::Tiny with Moo .SH MANUAL .IX Header "MANUAL" .SS "Type Constraints" .IX Subsection "Type Constraints" Consider the following basic Moo class: .PP .Vb 3 \& package Horse { \& use Moo; \& use namespace::autoclean; \& \& has name => ( is => \*(Aqro\*(Aq ); \& has gender => ( is => \*(Aqro\*(Aq ); \& has age => ( is => \*(Aqrw\*(Aq ); \& has children => ( is => \*(Aqro\*(Aq, default => sub { [] } ); \& } .Ve .PP Code like this seems simple enough: .PP .Vb 3 \& my $br = Horse\->new(name => "Bold Ruler", gender => \*(Aqm\*(Aq, age => 16); \& push @{ $br\->children }, \& Horse\->new(name => \*(AqSecretariat\*(Aq, gender => \*(Aqm\*(Aq, age => 0); .Ve .PP However, once you step away from very simple use of the class, things can start to go wrong. When we push a new horse onto \f(CW\*(C`@{ $br\->children }\*(C'\fR, we are assuming that \f(CW\*(C`$br\->children\*(C'\fR returned an arrayref. .PP What if the code that created the \f(CW$br\fR horse had instantiated it like this? .PP .Vb 1 \& my $br = Horse\->new(name => "Bold Ruler", children => \*(Aqno\*(Aq); .Ve .PP It is for this reason that it's useful for the Horse class to perform some basic sanity-checking on its own attributes. .PP .Vb 4 \& package Horse { \& use Moo; \& use Types::Standard qw( Str Num ArrayRef ); \& use namespace::autoclean; \& \& has name => ( is => \*(Aqro\*(Aq, isa => Str ); \& has gender => ( is => \*(Aqro\*(Aq, isa => Str ); \& has age => ( is => \*(Aqrw\*(Aq, isa => Num ); \& has children => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef, \& default => sub { return [] }, \& ); \& } .Ve .PP Now, if you instantiate a horse like this, it will throw an error: .PP .Vb 1 \& my $br = Horse\->new(name => "Bold Ruler", children => \*(Aqno\*(Aq); .Ve .PP The first type constraint we used here was \fBStr\fR. This is type constraint that requires values to be strings. .PP Note that although \f(CW\*(C`undef\*(C'\fR is not a string, the empty string is still a string and you will often want to check that a string is non-empty. We could have done this: .PP .Vb 2 \& use Types::Common::String qw( NonEmptyStr ); \& has name => ( is => \*(Aqro\*(Aq, isa => NonEmptyStr ); .Ve .PP While most of the type constraints we will use in this manual are defined in Types::Standard, the Types::Common::String type library also defines many useful type constraints. .PP We have required the horse's age to be a number. This is also a common, useful type constraint. If we want to make sure it's a whole number, we could use: .PP .Vb 2 \& use Types::Standard qw( Int ); \& has age => ( is => \*(Aqrw\*(Aq, isa => Int ); .Ve .PP Or because negative numbers make little sense as an age: .PP .Vb 2 \& use Types::Common::Numeric qw( PositiveOrZeroInt ); \& has age => ( is => \*(Aqrw\*(Aq, isa => PositiveOrZeroInt ); .Ve .PP The Types::Common::Numeric library defines many useful subtypes of \&\fBInt\fR and \fBNum\fR, such as \fBPositiveInt\fR and \fBPositiveOrZeroInt\fR. .PP The last type constraint we've used in this example is \fBArrayRef\fR. This requires the value to be a reference to an array. .PP Types::Standard also provides \fBHashRef\fR and \fBCodeRef\fR type constraints. An example of using the latter: .PP .Vb 8 \& package Task { \& use Moo; \& use Types::Standard qw( CodeRef Bool ); \& has on_success => ( is => \*(Aqro\*(Aq, isa => CodeRef ); \& has on_failure => ( is => \*(Aqro\*(Aq, isa => CodeRef ); \& has finished => ( is => \*(Aqro\*(Aq, isa => Bool, default => 0 ); \& ...; \& } \& \& my $task = Task\->new( \& on_success => sub { ... }, \& on_failure => sub { ... }, \& ..., \& ); .Ve .PP The \fBBool\fR type constraint accepts "1" as a true value, and "0", "", or undef as false values. No other values are accepted. .PP There exists an \fBObject\fR type constraint that accepts any blessed object. .PP .Vb 4 \& package Horse { \& use Moo; \& use Types::Standard qw( Object ); \& use namespace::autoclean; \& \& ...; # name, gender, age, children \& has father => ( is => \*(Aqro\*(Aq, isa => Object ); \& has mother => ( is => \*(Aqro\*(Aq, isa => Object ); \& } .Ve .PP Finally, another useful type constraint to know about is \fBAny\fR: .PP .Vb 2 \& use Types::Standard qw( Any ); \& has stuff => ( is => \*(Aqrw\*(Aq, isa => Any ); .Ve .PP This type constraint allows any value; it is essentially the same as not doing any type check, but makes your intent clearer. Where possible, Type::Tiny will optimize away this type check, so it should have little (if any) impact on performance. .SS "Parameterized Types" .IX Subsection "Parameterized Types" Let's imagine we want to keep track of our horse's race wins: .PP .Vb 4 \& package Horse { \& use Moo; \& use Types::Standard qw( Str Num ArrayRef ); \& use namespace::autoclean; \& \& ...; # name, gender, age, children \& has wins => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef, \& default => sub { return [] }, \& ); \& } .Ve .PP We can create a horse like this: .PP .Vb 6 \& my $br = Horse\->new( \& name => "Bold Ruler", \& gender => \*(Aqm\*(Aq, \& age => 4, \& wins => ["Futurity Stakes 1956", "Juvenile Stakes 1956"], \& ); .Ve .PP The list of wins is an arrayref of strings. The \fBArrayRef\fR type constraint prevents it from being set to a hashref, for example, but it doesn't ensure that everything in the arrayref is a string. To do that, we need to parameterize the type constraint: .PP .Vb 5 \& has wins => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef[Str], \& default => sub { return [] }, \& ); .Ve .PP Thanks to the \fBArrayRef[Str]\fR parameterized type, the constructor will throw an error if the arrayref you pass to it contains anything non-string. .PP An alternative way of writing this is: .PP .Vb 5 \& has wins => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef\->of(Str), \& default => sub { return [] }, \& ); .Ve .PP Which way you choose is largely a style preference. TIMTOWTDI! .PP Note that although the constructor and any setter/accessor method will perform type checks, it is possible to bypass them using: .PP .Vb 1 \& push @{ $br\->wins }, $not_a_string; .Ve .PP The constructor isn't being called here, and although the accessor \fIis\fR being called, it's being called as a reader, not a writer, so never gets an opportunity to inspect the value being added. (It is possible to use \&\f(CW\*(C`tie\*(C'\fR to solve this, but that will be covered later.) .PP And of course, if you directly poke at the underlying hashref of the object, all bets are off: .PP .Vb 1 \& $br\->{wins} = $not_an_arrayref; .Ve .PP So type constraints do have limitations. Careful API design (and not circumventing the proper API) can help. .PP The \fBHashRef\fR type constraint can also be parameterized: .PP .Vb 5 \& package Design { \& use Moo; \& use Types::Standard qw( HashRef Str ); \& has colours => ( is => \*(Aqro\*(Aq, isa => HashRef[Str] ); \& } \& \& my $eiffel65 = Design\->new( \& colours => { house => "blue", little_window => "blue" }, \& ); .Ve .PP The \fBHashRef[Str]\fR type constraint ensures the \fIvalues\fR of the hashref are strings; it doesn't check the keys of the hashref because keys in Perl hashes are always strings! .PP If you do need to constrain the keys, it is possible to use a parameterized \&\fBMap\fR constraint: .PP .Vb 3 \& use Types::Common::String qw( NonEmptyStr ); \& use Types::Standard qw( Map ); \& has colours => ( is => \*(Aqro\*(Aq, isa => Map[NonEmptyStr, NonEmptyStr] ); .Ve .PP \&\fBMap\fR takes two parameters; the first is a type to check keys against and the second is a type to check values against. .PP Another useful type constraint is the \fBTuple\fR type constraint. .PP .Vb 3 \& use Types::Standard qw( ArrayRef Tuple ); \& use Types::Common::Numeric qw( PositiveInt ); \& use Types::Common::String qw( NonEmptyStr ); \& \& has wins => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef[ Tuple[PositiveInt, NonEmptyStr] ], \& default => sub { return [] }, \& ); .Ve .PP The \fBTuple[PositiveInt, NonEmptyStr]\fR type constraint checks that a value is a two-element arrayref where the first element is a positive integer and the second element is a non-empty string. For example: .PP .Vb 7 \& my $br = Horse\->new( \& name => "Bold Ruler", \& wins => [ \& [ 1956, "Futurity Stakes" ], \& [ 1956, "Juvenile Stakes" ], \& ], \& ); .Ve .PP As you can see, parameterized type constraints may be nested to arbitrary depth, though of course the more detailed your checks become, the slower they will perform. .PP It is possible to have tuples with variable length. For example, we may wish to include the jockey name in our race wins when it is known. .PP .Vb 3 \& use Types::Standard qw( ArrayRef Tuple Optional ); \& use Types::Common::Numeric qw( PositiveInt ); \& use Types::Common::String qw( NonEmptyStr ); \& \& has wins => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef[ \& Tuple[ PositiveInt, NonEmptyStr, Optional[NonEmptyStr] ] \& ], \& default => sub { return [] }, \& ); .Ve .PP The third element will be checked if it is present, but forgiven if it is absent. .PP Or we could just allow tuples to contain an arbitrary list of strings after the year and race name: .PP .Vb 3 \& use Types::Standard qw( ArrayRef Tuple Str Slurpy ); \& use Types::Common::Numeric qw( PositiveInt ); \& use Types::Common::String qw( NonEmptyStr ); \& \& has wins => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef[ \& Tuple[ PositiveInt, NonEmptyStr, Slurpy[ ArrayRef[Str] ] ] \& ], \& default => sub { return [] }, \& ); .Ve .PP The \fBSlurpy[ ArrayRef[Str] ]\fR type will "slurp" all the remaining items in the tuple into an arrayref and check it against \fBArrayRef[Str]\fR. .PP It's even possible to do this: .PP .Vb 3 \& use Types::Standard qw( ArrayRef Tuple Any Slurpy ); \& use Types::Common::Numeric qw( PositiveInt ); \& use Types::Common::String qw( NonEmptyStr ); \& \& has wins => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef[ \& Tuple[ PositiveInt, NonEmptyStr, Slurpy[Any] ] \& ], \& default => sub { return [] }, \& ); .Ve .PP With this type constraint, any elements after the first two will be slurped into an arrayref and we don't check that arrayref at all. (In fact, the implementation of the \fBTuple\fR type is smart enough to not bother creating the temporary arrayref to check.) .PP \&\fBDict\fR is the equivalent of \fBTuple\fR for checking values of hashrefs. .PP .Vb 3 \& use Types::Standard qw( ArrayRef Dict Optional ); \& use Types::Common::Numeric qw( PositiveInt ); \& use Types::Common::String qw( NonEmptyStr ); \& \& has wins => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef[ \& Dict[ \& year => PositiveInt, \& race => NonEmptyStr, \& jockey => Optional[NonEmptyStr], \& ], \& ], \& default => sub { return [] }, \& ); .Ve .PP An example of using it: .PP .Vb 7 \& my $br = Horse\->new( \& name => "Bold Ruler", \& wins => [ \& { year => 1956, race => "Futurity Stakes", jockey => "Eddie" }, \& { year => 1956, race => "Juvenile Stakes" }, \& ], \& ); .Ve .PP The \fBSlurpy\fR type does work for \fBDict\fR too: .PP .Vb 6 \& Dict[ \& year => PositiveInt, \& race => NonEmptyStr, \& jockey => Optional[NonEmptyStr], \& () => Slurpy[ HashRef[Str] ], # other Str values allowed \& ] .Ve .PP And \f(CW\*(C`Slurpy[Any]\*(C'\fR means what you probably think it means: .PP .Vb 6 \& Dict[ \& year => PositiveInt, \& race => NonEmptyStr, \& jockey => Optional[NonEmptyStr], \& () => Slurpy[Any], # allow hashref to contain absolutely anything else \& ] .Ve .PP Going back to our first example, there's an opportunity to refine our \&\fBArrayRef\fR constraint: .PP .Vb 4 \& package Horse { \& use Moo; \& use Types::Standard qw( Str Num ArrayRef ); \& use namespace::autoclean; \& \& has name => ( is => \*(Aqro\*(Aq, isa => Str ); \& has gender => ( is => \*(Aqro\*(Aq, isa => Str ); \& has age => ( is => \*(Aqrw\*(Aq, isa => Num ); \& has children => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef[ InstanceOf["Horse"] ], \& default => sub { return [] }, \& ); \& } .Ve .PP The \fBInstanceOf["Horse"]\fR type constraint checks that a value is a blessed object in the Horse class. So the horse's children should be an arrayref of other Horse objects. .PP Internally it just checks \f(CW\*(C`$_\->isa("Horse")\*(C'\fR on each item in the arrayref. .PP It is sometimes useful to instead check \f(CW\*(C`$_\->DOES($role)\*(C'\fR or \&\f(CW\*(C`$_\->can($method)\*(C'\fR on an object. For example: .PP .Vb 3 \& package MyAPI::Client { \& use Moo; \& use Types::Standard qw( HasMethods ); \& \& has ua => (is => \*(Aqro\*(Aq, isa => HasMethods["get", "post"] ); \& } .Ve .PP The \fBConsumerOf\fR and \fBHasMethods\fR parameterizable types allow you to easily check roles and methods of objects. .PP The \fBEnum\fR parameterizable type allows you to accept a more limited set of string values. For example: .PP .Vb 2 \& use Types::Standard qw( Enum ); \& has gender => ( is => \*(Aqro\*(Aq, isa => Enum["m","f"] ); .Ve .PP Or if you want a little more flexibility, you can use \fBStrMatch\fR which allows you to test strings against a regular expression: .PP .Vb 2 \& use Types::Standard qw( StrMatch ); \& has gender => ( is => \*(Aqro\*(Aq, isa => StrMatch[qr/^[MF]/i] ); .Ve .PP Or \fBStrLength\fR to check the maximum and minimum length of a string: .PP .Vb 2 \& use Types::Common::String qw( StrLength ); \& has name => ( is => \*(Aqro\*(Aq, isa => StrLength[3, 100] ); .Ve .PP The maximum can be omitted. .PP Similarly, the maximum and minimum values for a numeric type can be expressed using \fBIntRange\fR and \fBNumRange\fR: .PP .Vb 3 \& use Types::Common::Numeric qw( IntRange ); \& # values over 200 are probably an input error \& has age => ( is => \*(Aqro\*(Aq, isa => IntRange[0, 200] ); .Ve .PP Parameterized type constraints are one of the most powerful features of Type::Tiny, allowing a small set of constraints to be combined in useful ways. .SS "Type Coercions" .IX Subsection "Type Coercions" It is often good practice to be liberal in what you accept. .PP .Vb 4 \& package Horse { \& use Moo; \& use Types::Standard qw( Str Num ArrayRef Bool ); \& use namespace::autoclean; \& \& ...; # name, gender, age, children, wins \& has is_alive => ( is => \*(Aqrw\*(Aq, isa => Bool, coerce => 1 ); \& } .Ve .PP The \f(CW\*(C`coerce\*(C'\fR option indicates that if a value is given which \fIdoes not\fR pass the \fBBool\fR type constraint, then it should be coerced (converted) into something that does. .PP The definition of \fBBool\fR says that to convert a non-boolean to a bool, you just do \f(CW\*(C`!! $non_bool\*(C'\fR. So all of the following will be living horses: .PP .Vb 3 \& Horse\->new(is_alive => 42) \& Horse\->new(is_alive => []) \& Horse\->new(is_alive => "false") # in Perl, string "false" is true! .Ve .PP \&\fBBool\fR is the only type constraint in Types::Standard that has a coercion defined for it. The \fBNumericCode\fR, \fBUpperCaseStr\fR, \fBLowerCaseStr\fR, \&\fBUpperCaseSimpleStr\fR, and \fBLowerCaseSimpleStr\fR types from Types::Common::String also have conversions defined. .PP The other built-in constraints do not define any coercions because it would be hard to agree on what it means to coerce from, say, a \fBHashRef\fR to an \fBArrayRef\fR. Do we keep the keys? The values? Both? .PP But it is pretty simple to add your own coercions! .PP .Vb 9 \& use Types::Standard qw( ArrayRef HashRef Str ); \& has things => ( \& is => \*(Aqrw\*(Aq, \& isa => ArrayRef\->plus_coercions( \& HashRef, sub { [ values %$_ ] }, \& Str, sub { [ split /;/, $_ ] }, \& ), \& coerce => 1, \& ); .Ve .PP (Don't ever forget the \f(CW\*(C`coerce => 1\*(C'\fR!) .PP If a hashref is provided, the values will be used, and if a string is provided, it will be split on the semicolon. Of course, if an arrayref if provided, it already passes the type constraint, so no conversion is necessary. .PP The coercions should be pairs of "from types" and code to coerce the value. The code can be a coderef (as above) or just string of Perl code (as below). Strings of Perl code can usually be optimized better by Type::Tiny's internals, so are generally preferred. Thanks to Perl's \&\f(CW\*(C`q{...}\*(C'\fR operator, they can look just as clean and pretty as coderefs. .PP .Vb 9 \& use Types::Standard qw( ArrayRef HashRef Str ); \& has things => ( \& is => \*(Aqrw\*(Aq, \& isa => ArrayRef\->plus_coercions( \& HashRef, q{ [ values %$_ ] }, \& Str, q{ [ split /;/, $_ ] }, \& ), \& coerce => 1, \& ); .Ve .PP Coercions are deeply applied automatically, so the following will do what you expect. .PP .Vb 5 \& has inputs => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef\->of(Bool), \& coerce => 1 \& ); .Ve .PP I am, of course, assuming you expect something like: .PP .Vb 1 \& my $coerced = [ map { !!$_ } @$orig ]; .Ve .PP If you were assuming that, congratulations! We are on the same wavelength. .PP And of course you can still add more coercions to the inherited ones... .PP .Vb 5 \& has inputs => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef\->of(Bool)\->plus_coercions(Str, sub {...}), \& coerce => 1 \& ); .Ve .SS "Type Defaults" .IX Subsection "Type Defaults" A previous example included: .PP .Vb 5 \& has children => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef, \& default => sub { return [] }, \& ); .Ve .PP It's actually pretty common that you'll want an arrayref attribute to default to being an empty arrayref, a numeric attribute to default to zero, etc. Type::Tiny provides a method for that: .PP .Vb 5 \& has children => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef, \& default => ArrayRef\->type_default, \& ); .Ve .PP Many of the types in Types::Standard have sensible type defaults defined. .SS "Method Parameters" .IX Subsection "Method Parameters" So far we have just concentrated on the definition of object attributes, but type constraints are also useful to validate method parameters. .PP Let's remember our attribute for keeping track of a horse's race wins: .PP .Vb 3 \& use Types::Standard qw( ArrayRef Tuple Optional ); \& use Types::Common::Numeric qw( PositiveInt ); \& use Types::Common::String qw( NonEmptyStr ); \& \& has wins => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef[ \& Tuple[ PositiveInt, NonEmptyStr, Optional[NonEmptyStr] ] \& ], \& default => sub { return [] }, \& ); .Ve .PP Because we don't trust outside code to push new entries onto this array, let's define a method in our class to do it. .PP .Vb 2 \& package Horse { \& ...; \& \& sub add_win { \& my $self = shift; \& my ($year, $race, $jockey) = @_; \& my $win = [ \& $year, \& $race, \& $jockey ? $jockey : (), \& ]; \& push @{ $self\->wins }, $win; \& return $self; \& } \& } .Ve .PP This works pretty well, but we're still not actually checking the values of \f(CW$year\fR, \f(CW$race\fR, and \f(CW$jockey\fR. Let's use Type::Params for that: .PP .Vb 5 \& package Horse { \& use Types::Common::Numeric qw( PositiveInt ); \& use Types::Common::String qw( NonEmptyStr ); \& use Type::Params qw( signature ); \& ...; \& \& sub add_win { \& state $check = signature( \& method => 1, # allow for $self \& positional => [ \& PositiveInt, \& NonEmptyStr, \& NonEmptyStr, { optional => 1 }, \& ], \& ); \& \& my ( $self, $year, $race, $jockey ) = $check\->(@_); \& my $win = [ \& $year, \& $race, \& $jockey ? $jockey : (), \& ]; \& push @{ $self\->wins }, $win; \& return $self; \& } \& } .Ve .PP The first time this method is called, it will compile a coderef called \&\f(CW$check\fR. Then every time it is run, \f(CW$check\fR will be called to check the method's parameters. It will throw an exception if they fail. \f(CW$check\fR will also perform coercions if types have them (and you don't even need to remember \f(CW\*(C`coerce => 1\*(C'\fR; it's automatic) and can even add in defaults: .PP .Vb 8 \& state $check = signature( \& method => 1, \& positional => [ \& PositiveInt, \& NonEmptyStr, \& NonEmptyStr, { default => sub { "Eddie" } }, \& ], \& ); .Ve .PP On older versions of Perl (prior to 5.10), \f(CW\*(C`state\*(C'\fR variables are not available. A workaround is to replace this: .PP .Vb 4 \& sub foo { \& state $x = bar(); \& ...; \& } .Ve .PP With this: .PP .Vb 7 \& { # outer braces prevent other subs seeing $x \& my $x; # declare $x before sub foo() \& sub foo { \& $x = bar(); \& ...; \& } \& } .Ve .PP (While we're having a general Perl syntax lesson, I'll note that \&\f(CW&$check\fR with an ampersand and no parentheses is a shortcut for \&\f(CW$check\->(@_)\fR and actually runs slightly faster because it reuses the \f(CW@_\fR array for the called coderef. A lot of people dislike calling subs with an ampersand, so we will stick to the \f(CW$check\->(@_)\fR syntax in these examples. But do consider using the shortcut!) .PP The generalized syntax for positional parameters in \f(CW\*(C`signature\*(C'\fR is: .PP .Vb 8 \& state $check = signature( \& %general_options, \& positional => [ \& TypeForFirstParam, \e%options_for_first_param, \& TypeForSecondParam, \e%options_for_second_param, \& ..., \& ], \& ); .Ve .PP As a shortcut for the \f(CW\*(C`{ optional => 1 }\*(C'\fR option, you can just use \&\fBOptional\fR like in \fBTuple\fR. .PP .Vb 8 \& state $check = signature( \& method => 1, \& positional => [ \& PositiveInt, \& NonEmptyStr, \& Optional[NonEmptyStr], \& ], \& ); .Ve .PP You can also use \f(CW0\fR and \f(CW1\fR as shortcuts for \fBOptional[Any]\fR and \&\fBAny\fR. The following checks that the first parameter is a positive integer, the second parameter is required (but doesn't care what value it is) and the third parameter is allowed but not required. .PP .Vb 1 \& state $check = signature positional => [ PositiveInt, 1, 0 ]; .Ve .PP It is possible to accept a variable number of values using \fBSlurpy\fR: .PP .Vb 6 \& package Horse { \& use Types::Common::Numeric qw( PositiveInt ); \& use Types::Common::String qw( NonEmptyStr ); \& use Types::Standard qw( ArrayRef Slurpy ); \& use Type::Params qw( signature ); \& ...; \& \& sub add_wins_for_year { \& state $check = signature( \& method => 1, \& positional => [ \& PositiveInt, \& Slurpy[ ArrayRef[NonEmptyStr] ], \& ], \& ); \& \& my ( $self, $year, $races ) = $check\->(@_); \& for my $race (@$races) { \& push @{ $self\->wins }, [$year, $race]; \& } \& return $self; \& } \& } .Ve .PP It would be called like this: .PP .Vb 5 \& $bold_ruler\->add_wins_for_year( \& 1956, \& "Futurity Stakes", \& "Juvenile Stakes", \& ); .Ve .PP The additional parameters are slurped into an arrayref and checked against \&\fBArrayRef[NonEmptyStr]\fR. .PP Optional parameters are only allowed after required parameters, and \fBSlurpy\fR parameters are only allowed at the end. (And there can only be a at most one \fBSlurpy\fR parameter!) .PP For methods that accept more than one or two parameters, it is often a good idea to provide them as a hash. For example: .PP .Vb 5 \& $horse\->add_win( \& year => 1956, \& race => "Futurity Stakes", \& jockey => "Eddie", \& ); .Ve .PP This can make your code more readable. .PP To accept named parameters, use the \f(CW\*(C`named\*(C'\fR option instead of \f(CW\*(C`positional\*(C'\fR. .PP .Vb 5 \& package Horse { \& use Types::Common::Numeric qw( PositiveInt ); \& use Types::Common::String qw( NonEmptyStr ); \& use Type::Params qw( signature ); \& ...; \& \& sub add_win { \& state $check = signature( \& method => 1, \& named => [ \& year => PositiveInt, \& race => NonEmptyStr, \& jockey => NonEmptyStr, { optional => 1 }, \& ], \& ); \& \& my ( $self, $arg ) = $check\->(@_); \& my $win = [ \& $arg\->year, \& $arg\->race, \& $arg\->has_jockey ? $arg\->jockey : (), \& ]; \& push @{ $self\->wins }, $win; \& return $self; \& } \& } .Ve .PP The \f(CW\*(C`named\*(C'\fR option will bundle all of your named arguments into an object \&\f(CW$arg\fR. It allows your method to be called with a list of name-value pairs or a hashref: .PP .Vb 5 \& $horse\->add_win( \& year => 1956, \& race => "Futurity Stakes", \& jockey => "Eddie", \& ); \& \& $horse\->add_win( { \& year => 1956, \& race => "Juvenile Stakes", \& } ); .Ve .PP It is also possible for your check to \fIaccept\fR named parameters but \&\fIreturn\fR a positional list of parameters, using \f(CW\*(C`named_to_list\*(C'\fR. .PP .Vb 5 \& package Horse { \& use Types::Common::Numeric qw( PositiveInt ); \& use Types::Common::String qw( NonEmptyStr ); \& use Type::Params qw( signature ); \& ...; \& \& sub add_win { \& state $check = signature( \& method => 1, \& named => [ \& year => PositiveInt, \& race => NonEmptyStr, \& jockey => NonEmptyStr, { optional => 1 }, \& ], \& named_to_list => 1, \& ); \& \& my ( $self, $year, $race, $jockey ) = $check\->(@_); \& my $win = [ \& $year, \& $race, \& $jockey ? $jockey : (), \& ]; \& push @{ $self\->wins }, $win; \& return $self; \& } \& } .Ve .PP Optional and Slurpy named parameters are supported as you'd expect. .PP For more information on Type::Params, and third-party alternatives, see Type::Tiny::Manual::Params. .SH "NEXT STEPS" .IX Header "NEXT STEPS" Congratulations! I know this was probably a lot to take in, but you've covered all of the essentials. .PP You can now set type constraints and coercions for attributes and method parameters in Moo! You are familiar with a lot of the most important and useful type constraints and understand parameterization and how it can be used to build more specific type constraints. .PP (And I'll let you in on a secret. Using Type::Tiny with Moose or Mouse instead of Moo is exactly the same. You can just replace \&\f(CW\*(C`use Moo\*(C'\fR with \f(CW\*(C`use Moose\*(C'\fR in any of these examples and they should work fine!) .PP Here's your next step: .IP \(bu 4 Type::Tiny::Manual::UsingWithMoo2 .Sp Advanced use of Type::Tiny with Moo, including unions and intersections, \&\f(CW\*(C`stringifies_to\*(C'\fR, \f(CW\*(C`numifies_to\*(C'\fR, \f(CW\*(C`with_attribute_values\*(C'\fR, and \f(CW\*(C`where\*(C'\fR. .SH NOTES .IX Header "NOTES" On very old versions of Moo \f(CW\*(C`coerce => 1\*(C'\fR is not supported. Instead you will need to provide a coderef or object overloading \f(CW\*(C`&{}\*(C'\fR to coerce. Type::Tiny can provide you with an overloaded object. .PP .Vb 4 \& package Horse { \& use Moo; \& use Types::Standard qw( Str Num ArrayRef Bool ); \& use namespace::autoclean; \& \& ...; # name, gender, age, children, wins \& has is_alive => ( \& is => \*(Aqrw\*(Aq, \& isa => Bool, \& coerce => Bool\->coercion, # overloaded object \& ); \& } .Ve .PP If you have a very old version of Moo, please upgrade to at least Moo 1.006000 which was the version that added support for \f(CW\*(C`coerce => 1\*(C'\fR. .SH AUTHOR .IX Header "AUTHOR" Toby Inkster . .SH "COPYRIGHT AND LICENCE" .IX Header "COPYRIGHT AND LICENCE" This software is copyright (c) 2013\-2014, 2017\-2023 by Toby Inkster. .PP This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. .SH "DISCLAIMER OF WARRANTIES" .IX Header "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.