.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.43) .\" .\" 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 .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . 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::UsingWithMoo2 3pm" .TH Type::Tiny::Manual::UsingWithMoo2 3pm "2023-07-21" "perl v5.36.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::UsingWithMoo2 \- advanced use of Type::Tiny with Moo .SH "MANUAL" .IX Header "MANUAL" .SS "What is a Type?" .IX Subsection "What is a Type?" So far all the examples have shown you how to work with types, but we haven't looked at what a type actually \fIis\fR. .PP .Vb 2 \& use Types::Standard qw( Int ); \& my $type = Int; .Ve .PP \&\f(CW\*(C`Int\*(C'\fR in the above code is just a function called with zero arguments which returns a blessed Perl object. It is this object that defines what the \fBInt\fR type is and is responsible for checking values meet its definition. .PP .Vb 2 \& use Types::Standard qw( HashRef Int ); \& my $type = HashRef[Int]; .Ve .PP The \f(CW\*(C`HashRef\*(C'\fR function, if called with no parameters returns the object defining the \fBHashRef\fR type, just like the \f(CW\*(C`Int\*(C'\fR function did before. But the difference here is that it's called with a parameter, an arrayref containing the \fBInt\fR type object. It uses this to make the \fBHashRef[Int]\fR type and returns that. .PP Like any object, you can call methods on it. The most important methods to know about are: .PP .Vb 3 \& # check the value and return a boolean \& # \& $type\->check($value); \& \& # return an error message about $value failing the type check \& # but don\*(Aqt actually check the value \& # \& $type\->get_message($value); \& \& # coerce the value \& # \& my $coerced = $type\->coerce($value); .Ve .PP We've already seen some other methods earlier in the tutorial. .PP .Vb 3 \& # create a new type, same as the old type, but that has coercions \& # \& my $new_type = $type\->plus_coercions( ... ); \& \& # different syntax for parameterized types \& # \& my $href = HashRef; \& my $int = Int; \& my $href_of_int = $href\->of($int); .Ve .PP So now you should understand this: .PP .Vb 3 \& use Types::Standard qw( ArrayRef Dict Optional ); \& use Types::Common::Numeric qw( PositiveInt ); \& use Types::Common::String qw( NonEmptyStr ); \& \& my $RaceInfo = Dict[ \& year => PositiveInt, \& race => NonEmptyStr, \& jockey => Optional[NonEmptyStr], \& ]; \& \& has latest_event => ( is => \*(Aqrw\*(Aq, isa => $RaceInfo ); \& has wins => ( is => \*(Aqrw\*(Aq, isa => ArrayRef[$RaceInfo] ); \& has losses => ( is => \*(Aqrw\*(Aq, isa => ArrayRef[$RaceInfo] ); .Ve .PP This can help you avoid repetition if you have a complex parameterized type that you need to reuse a few times. .ie n .SS """where""" .el .SS "\f(CWwhere\fP" .IX Subsection "where" One of the most useful methods you can call on a type object is \&\f(CW\*(C`where\*(C'\fR. .PP .Vb 1 \& use Types::Standard qw( Int ); \& \& has lucky_number => ( \& is => \*(Aqro\*(Aq, \& isa => Int\->where(sub { $_ != 13 }), \& ); .Ve .PP I think you already understand what it does. It creates a new type constraint on the fly, restricting the original type. .PP Like with coercions, these restrictions can be expressed as a coderef or as a string of Perl code, operating on the \f(CW$_\fR variable. And like with coercions, using a string of code will result in better performance. .PP .Vb 1 \& use Types::Standard qw( Int ); \& \& has lucky_number => ( \& is => \*(Aqro\*(Aq, \& isa => Int\->where(q{ $_ != 13 }), \& ); .Ve .PP Let's coerce a hashref of strings from an even-sized arrayref of strings: .PP .Vb 1 \& use Types::Standard qw( HashRef ArrayRef Str ); \& \& has stringhash => ( \& is => \*(Aqro\*(Aq, \& isa => HashRef\->of(Str)\->plus_coercions( \& ArrayRef\->of(Str)\->where(q{ @$_ % 2 == 0 }), q{ \& my %h = @$_; \& \e%h; \& }, \& ), \& coerce => 1, # never forget! \& ); .Ve .PP If you understand that, you really are in the advanced class. Congratulations! .SS "Unions" .IX Subsection "Unions" Sometimes you want to accept one thing or another thing. This is pretty easy with Type::Tiny. .PP .Vb 1 \& use Types::Standard qw( HashRef ArrayRef Str ); \& \& has strings => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef[Str] | HashRef[Str], \& ); .Ve .PP Type::Tiny overloads the bitwise or operator so stuff like this should \&\*(L"just work\*(R". .PP That said, now any code that calls \f(CW\*(C`$self\->strings\*(C'\fR will probably need to check if the value is an arrayref or a hashref before doing anything with it. So it may be simpler overall if you just choose one of the options and coerce the other one into it. .SS "Intersections" .IX Subsection "Intersections" Similar to a union is an intersection. .PP .Vb 3 \& package MyAPI::Client { \& use Moo; \& use Types::Standard qw( HasMethods InstanceOf ); \& \& has ua => ( \& is => \*(Aqro\*(Aq, \& isa => (InstanceOf["MyUA"]) & (HasMethods["store_cookie"]), \& ); \& } .Ve .PP Here we are checking that the \s-1UA\s0 is an instance of the MyUA class and also offers the \f(CW\*(C`store_cookie\*(C'\fR method. Perhaps \f(CW\*(C`store_cookie\*(C'\fR isn't provided by the MyUA class itself, but several subclasses of MyUA provide it. .PP Intersections are not useful as often as unions are. This is because they often make no sense. \f(CW\*(C`(ArrayRef) & (HashRef)\*(C'\fR would be a reference which was simultaneously pointing to an array and a hash, which is impossible. .PP Note that when using intersections, it is good practice to put parentheses around each type. This is to disambiguate the meaning of \f(CW\*(C`&\*(C'\fR for Perl, because Perl uses it as the bitwise and operator but also as the sigil for subs. .SS "Complements" .IX Subsection "Complements" For any type \fBFoo\fR there is a complementary type \fB~Foo\fR (pronounced \&\*(L"not Foo\*(R"). .PP .Vb 3 \& package My::Class { \& use Moo; \& use Types::Standard qw( ArrayRef CodeRef ); \& \& has things => ( is => \*(Aqro\*(Aq, isa => ArrayRef[~CodeRef] ); \& } .Ve .PP \&\f(CW\*(C`things\*(C'\fR is now an arrayref of anything except coderefs. .PP If you need a number that is \fInot\fR an integer: .PP .Vb 1 \& Num & ~Int .Ve .PP Types::Standard includes two types which are complements of each other: \&\fBUndef\fR and \fBDefined\fR. .PP \&\fBNegativeInt\fR might seem to be the complement of \fBPositiveOrZeroInt\fR but when you think about it, it is not. There are values that fall into neither category, such as non-integers, non-numeric strings, references, undef, etc. .ie n .SS """stringifies_to"" and ""numifies_to""" .el .SS "\f(CWstringifies_to\fP and \f(CWnumifies_to\fP" .IX Subsection "stringifies_to and numifies_to" The \fBObject\fR type constraint provides \f(CW\*(C`stringifies_to\*(C'\fR and \f(CW\*(C`numifies_to\*(C'\fR methods which are probably best explained by examples. .PP \&\f(CW\*(C`Object\->numifies_to(Int)\*(C'\fR means any object where \f(CW\*(C`0 + $object\*(C'\fR is an integer. .PP \&\f(CW\*(C`Object\->stringifies_to(StrMatch[$re])\*(C'\fR means any object where \&\f(CW"$object"\fR matches the regular expression. .PP \&\f(CW\*(C`Object\->stringifies_to($re)\*(C'\fR also works as a shortcut. .PP \&\f(CW\*(C`Object\->numifies_to($coderef)\*(C'\fR and \&\f(CW\*(C`Object\->stringifies_to($coderef)\*(C'\fR also work, where the coderef checks \&\f(CW$_\fR and returns a boolean. .PP Other types which are also logically objects, such as parameterized \&\fBHasMethods\fR, \fBInstanceOf\fR, and \fBConsumerOf\fR should also provide \&\f(CW\*(C`stringifies_to\*(C'\fR and \f(CW\*(C`numifies_to\*(C'\fR methods. .PP \&\f(CW\*(C`stringifies_to\*(C'\fR and \f(CW\*(C`numifies_to\*(C'\fR work on unions if \fIall\fR of the type constraints in the union offer the method. .PP \&\f(CW\*(C`stringifies_to\*(C'\fR and \f(CW\*(C`numifies_to\*(C'\fR work on intersections if \&\fIat least one of\fR of the type constraints in the intersection offers the method. .ie n .SS """with_attribute_values""" .el .SS "\f(CWwith_attribute_values\fP" .IX Subsection "with_attribute_values" Another one that is probably best explained using an example: .PP .Vb 2 \& package Horse { \& use Types::Standard qw( Enum Object ); \& \& has gender => ( \& is => \*(Aqro\*(Aq, \& isa => Enum[\*(Aqm\*(Aq, \*(Aqf\*(Aq], \& ); \& has father => ( \& is => \*(Aqro\*(Aq, \& isa => Object\->with_attribute_values(gender => Enum[\*(Aqm\*(Aq]), \& ); \& has mother => ( \& is => \*(Aqro\*(Aq, \& isa => Object\->with_attribute_values(gender => Enum[\*(Aqf\*(Aq]), \& ); \& } .Ve .PP In this example when you set a horse's father, it will call \&\f(CW\*(C`$father\->gender\*(C'\fR and check that it matches \fBEnum['m']\fR. .PP This method is in the same family as \f(CW\*(C`stringifies_as\*(C'\fR and \f(CW\*(C`numifies_as\*(C'\fR, so like those, it only applies to \fBObject\fR and similar type constraints, can work on unions/intersections under the same circumstances, and will also accept coderefs and regexps. .PP .Vb 8 \& has father => ( \& is => \*(Aqro\*(Aq, \& isa => Object\->with_attribute_values(gender => sub { $_ eq \*(Aqm\*(Aq }), \& ); \& has mother => ( \& is => \*(Aqro\*(Aq, \& isa => Object\->with_attribute_values(gender => qr/^f/i), \& ); .Ve .PP All of \f(CW\*(C`stringifies_as\*(C'\fR, \f(CW\*(C`numifies_as\*(C'\fR, and \f(CW\*(C`with_attributes_as\*(C'\fR are really just wrappers around \f(CW\*(C`where\*(C'\fR. The following two are roughly equivalent: .PP .Vb 1 \& my $type1 = Object\->with_attribute_values(foo => Int, bar => Num); \& \& my $type2 = Object\->where(sub { \& Int\->check( $_\->foo ) and Num\->check( $_\->bar ) \& }); .Ve .PP The first will result in better performing code though. .SS "Tied Variables" .IX Subsection "Tied Variables" It is possible to tie variables to a type constraint. .PP .Vb 1 \& use Types::Standard qw(Int); \& \& tie my $n, Int, 4; \& \& print "$n\en"; # says "4" \& $n = 5; # ok \& $n = "foo"; # dies .Ve .PP You can also tie arrays: .PP .Vb 2 \& tie my @numbers, Int; \& push @numbers, 1 .. 10; .Ve .PP And hashes: .PP .Vb 3 \& tie my %numbers, Int; \& $numbers{lucky} = 7; \& $numbers{unlucky} = 13; .Ve .PP Earlier in the manual, it was mentioned that there is a problem with code like this: .PP .Vb 1 \& push @{ $horse\->children }, $non_horse; .Ve .PP This can be solved using tied variables. .PP .Vb 1 \& tie @{ $horse\->children }, InstanceOf["Horse"]; .Ve .PP Here is a longer example using builders and triggers. .PP .Vb 5 \& package Horse { \& use Moo; \& use Types::Standard qw( Str Num ArrayRef InstanceOf ); \& use Type::Params qw( signature ); \& use namespace::autoclean; \& \& my $ThisClass = InstanceOf[ _\|_PACKAGE_\|_ ]; \& \& has name => ( is => \*(Aqro\*(Aq, isa => Str ); \& has gender => ( is => \*(Aqro\*(Aq, isa => Str ); \& has age => ( is => \*(Aqrw\*(Aq, isa => Num ); \& has children => ( \& is => \*(Aqrw\*(Aq, \& isa => ArrayRef[$ThisClass], \& builder => "_build_children", \& trigger => sub { shift\->_trigger_children(@_) }, \& ); \& \& # tie a default arrayref \& sub _build_children { \& my $self = shift; \& tie my @kids, $ThisClass; \& \e@kids; \& } \& \& # this method will tie an arrayref provided by the caller \& sub _trigger_children { \& my $self = shift; \& my ($new) = @_; \& tie @$new, $ThisClass; \& } \& \& sub add_child { \& state $check = signature( \& method => $ThisClass, \& positional => [ $ThisClass ], \& ); \& my ( $self, $kid ) = &$check; \& push @{ $self\->children }, $kid; \& return $self; \& } \& } .Ve .PP Now it's pretty much impossible for the caller to make a mess by adding a non-horse as a child. .PP (Note there's a Types::Self module on \s-1CPAN\s0 that will define a \fBSelf\fR type meaning \fBInstanceOf[ _\|_PACKAGE_\|_ ]\fR for you!) .SH "NEXT STEPS" .IX Header "NEXT STEPS" Here's your next step: .IP "\(bu" 4 Type::Tiny::Manual::UsingWithMoo3 .Sp There's more than one way to do it! Alternative ways of using Type::Tiny, including type registries, exported functions, and \f(CW\*(C`dwim_type\*(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" \&\s-1THIS PACKAGE IS PROVIDED \*(L"AS IS\*(R" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\s0