HEX
Server: Apache
System: Linux s198.coreserver.jp 5.15.0-151-generic #161-Ubuntu SMP Tue Jul 22 14:25:40 UTC 2025 x86_64
User: nagasaki (10062)
PHP: 7.1.33
Disabled: NONE
Upload Files
File: //usr/local/share/man/man3/Type::Params.3pm
.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35)
.\"
.\" 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::Params 3"
.TH Type::Params 3 "2021-07-31" "perl v5.26.3" "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::Params \- Params::Validate\-like parameter validation using Type::Tiny type constraints and coercions
.SH "SYNOPSIS"
.IX Header "SYNOPSIS"
.Vb 3
\& use v5.12;
\& use strict;
\& use warnings;
\& 
\& package Horse {
\&   use Moo;
\&   use Types::Standard qw( Object );
\&   use Type::Params qw( compile );
\&   use namespace::autoclean;
\&   
\&   ...;   # define attributes, etc
\&   
\&   sub add_child {
\&     state $check = compile( Object, Object );  # method signature
\&     
\&     my ($self, $child) = $check\->(@_);         # unpack @_
\&     push @{ $self\->children }, $child;
\&     
\&     return $self;
\&   }
\& }
\& 
\& package main;
\& 
\& my $boldruler = Horse\->new;
\& 
\& $boldruler\->add_child( Horse\->new );
\& 
\& $boldruler\->add_child( 123 );   # dies (123 is not an Object!)
.Ve
.SH "STATUS"
.IX Header "STATUS"
This module is covered by the
Type-Tiny stability policy.
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
This documents the details of the Type::Params package.
Type::Tiny::Manual is a better starting place if you're new.
.PP
Type::Params uses Type::Tiny constraints to validate the parameters to a
sub. It takes the slightly unorthodox approach of separating validation
into two stages:
.IP "1." 4
Compiling the parameter specification into a coderef; then
.IP "2." 4
Using the coderef to validate parameters.
.PP
The first stage is slow (it might take a couple of milliseconds), but you
only need to do it the first time the sub is called. The second stage is
fast; according to my benchmarks faster even than the \s-1XS\s0 version of
Params::Validate.
.PP
If you're using a modern version of Perl, you can use the \f(CW\*(C`state\*(C'\fR keyword
which was a feature added to Perl in 5.10. If you're stuck on Perl 5.8, the
example from the \s-1SYNOPSIS\s0 could be rewritten as:
.PP
.Vb 3
\&   my $add_child_check;
\&   sub add_child {
\&     $add_child_check ||= compile( Object, Object );
\&     
\&     my ($self, $child) = $add_child_check\->(@_);  # unpack @_
\&     push @{ $self\->children }, $child;
\&     
\&     return $self;
\&   }
.Ve
.PP
Not quite as neat, but not awful either.
.PP
If you don't like the two step, there's a shortcut reducing it to one step:
.PP
.Vb 1
\&   use Type::Params qw( validate );
\&   
\&   sub add_child {
\&     my ($self, $child) = validate(\e@_, Object, Object);
\&     push @{ $self\->children }, $child;
\&     return $self;
\&   }
.Ve
.PP
Type::Params has a few tricks up its sleeve to make sure performance doesn't
suffer too much with the shortcut, but it's never going to be as fast as the
two stage compile/execute.
.SS "Functions"
.IX Subsection "Functions"
\fI\f(CI\*(C`compile(@spec)\*(C'\fI\fR
.IX Subsection "compile(@spec)"
.PP
Given specifications for positional parameters, compiles a coderef
that can check against them.
.PP
The generalized form of specifications for positional parameters is:
.PP
.Vb 8
\& state $check = compile(
\&   \e%general_opts,
\&   $type_for_arg_1, \e%opts_for_arg_1,
\&   $type_for_arg_2, \e%opts_for_arg_2,
\&   $type_for_arg_3, \e%opts_for_arg_3,
\&   ...,
\&   slurpy($slurpy_type),
\& );
.Ve
.PP
If a hashref of options is empty, it can simply be omitted. Much of the
time, you won't need to specify any options.
.PP
.Vb 7
\& # In this example, we omit all the hashrefs
\& #
\& my $check = compile(
\&   Str,
\&   Int,
\&   Optional[ArrayRef],
\& );
\& 
\& my ($str, $int, $arr) = $check\->("Hello", 42, []);   # ok
\& my ($str, $int, $arr) = $check\->("", \-1);            # ok
\& my ($str, $int, $arr) = $check\->("", \-1, "bleh");    # dies
.Ve
.PP
The coderef returned (i.e. \f(CW$check\fR) will check the arguments
passed to it conform to the spec (coercing them if appropriate),
and return them as a list if they do. If they don't, it will throw
an exception.
.PP
The first hashref, before any type constraints, is for general options
which affect the entire compiled coderef. Currently supported general
options are:
.ie n .IP """head"" \fBInt|ArrayRef[TypeTiny]\fR" 4
.el .IP "\f(CWhead\fR \fBInt|ArrayRef[TypeTiny]\fR" 4
.IX Item "head Int|ArrayRef[TypeTiny]"
Parameters to shift off \f(CW@_\fR before doing the main type check.
These parameters may also be checked, and cannot be optional or slurpy.
They may not have defaults.
.Sp
.Vb 5
\&  my $check = compile(
\&    { head => [ Int, Int ] },
\&    Str,
\&    Str,
\&  );
\&  
\&  # ... is basically the same as...
\&  
\&  my $check = compile(
\&    Int,
\&    Int,
\&    Str,
\&    Str,
\&  );
.Ve
.Sp
A number may be given if you do not care to check types:
.Sp
.Vb 5
\&  my $check = compile(
\&    { head => 2 },
\&    Str,
\&    Str,
\&  );
\&  
\&  # ... is basically the same as...
\&  
\&  my $check = compile(
\&    Any,
\&    Any,
\&    Str,
\&    Str,
\&  );
.Ve
.Sp
This is mostly useless for \f(CW\*(C`compile\*(C'\fR, but can be useful for
\&\f(CW\*(C`compile_named\*(C'\fR and \f(CW\*(C`compile_named_oo\*(C'\fR.
.ie n .IP """tail"" \fBInt|ArrayRef[TypeTiny]\fR" 4
.el .IP "\f(CWtail\fR \fBInt|ArrayRef[TypeTiny]\fR" 4
.IX Item "tail Int|ArrayRef[TypeTiny]"
Similar to \f(CW\*(C`head\*(C'\fR, but pops parameters off the end of \f(CW@_\fR instead.
This is actually useful for \f(CW\*(C`compile\*(C'\fR because it allows you to sneak in
some required parameters \fIafter\fR a slurpy or optional parameter.
.Sp
.Vb 4
\&  my $check = compile(
\&    { tail => [ CodeRef ] },
\&    slurpy ArrayRef[Str],
\&  );
\&  
\&  my ($strings, $coderef) = $check\->("foo", "bar", sub { ... });
.Ve
.ie n .IP """want_source"" \fBBool\fR" 4
.el .IP "\f(CWwant_source\fR \fBBool\fR" 4
.IX Item "want_source Bool"
Instead of returning a coderef, return Perl source code string. Handy
for debugging.
.ie n .IP """want_details"" \fBBool\fR" 4
.el .IP "\f(CWwant_details\fR \fBBool\fR" 4
.IX Item "want_details Bool"
Instead of returning a coderef, return a hashref of stuff including the
coderef. This is mostly for people extending Type::Params and I won't go
into too many details about what else this hashref contains.
.ie n .IP """description"" \fBStr\fR" 4
.el .IP "\f(CWdescription\fR \fBStr\fR" 4
.IX Item "description Str"
Description of the coderef that will show up in stack traces. Defaults to
\&\*(L"parameter validation for X\*(R" where X is the caller sub name.
.ie n .IP """subname"" \fBStr\fR" 4
.el .IP "\f(CWsubname\fR \fBStr\fR" 4
.IX Item "subname Str"
If you wish to use the default description, but need to change the sub name,
use this.
.ie n .IP """caller_level"" \fBInt\fR" 4
.el .IP "\f(CWcaller_level\fR \fBInt\fR" 4
.IX Item "caller_level Int"
If you wish to use the default description, but need to change the caller
level for detecting the sub name, use this.
.PP
The types for each parameter may be any Type::Tiny type constraint, or
anything that Type::Tiny knows how to coerce into a Type::Tiny type
constraint, such as a MooseX::Types type constraint or a coderef.
.PP
Type coercions are automatically applied for all types that have
coercions.
.PP
If you wish to avoid coercions for a type, use Type::Tiny's
\&\f(CW\*(C`no_coercions\*(C'\fR method.
.PP
.Vb 4
\& my $check = compile(
\&   Int,
\&   ArrayRef\->of(Bool)\->no_coercions,
\& );
.Ve
.PP
Note that having any coercions in a specification, even if they're not
used in a particular check, will slightly slow down \f(CW$check\fR
because it means that \f(CW$check\fR can't just check \f(CW@_\fR and return
it unaltered if it's valid — it needs to build a new array to return.
.PP
Optional parameters can be given using the \fBOptional[]\fR type
constraint. In the example above, the third parameter is optional.
If it's present, it's required to be an arrayref, but if it's absent,
it is ignored.
.PP
Optional parameters need to be \fIafter\fR required parameters in the
spec.
.PP
An alternative way to specify optional parameters is using a parameter
options hashref.
.PP
.Vb 5
\& my $check = compile(
\&   Str,
\&   Int,
\&   ArrayRef, { optional => 1 },
\& );
.Ve
.PP
The following parameter options are supported:
.ie n .IP """optional"" \fBBool\fR" 4
.el .IP "\f(CWoptional\fR \fBBool\fR" 4
.IX Item "optional Bool"
This is an alternative way of indicating that a parameter is optional.
.Sp
.Vb 5
\& state $check = compile(
\&   Int,
\&   Int, { optional => 1 },
\&   Optional[Int],
\& );
.Ve
.Sp
The two are not \fIexactly\fR equivalent. The exceptions thrown will
differ in the type name they mention. (\fBInt\fR versus \fBOptional[Int]\fR.)
.ie n .IP """default"" \fBCodeRef|Ref|Str|Undef\fR" 4
.el .IP "\f(CWdefault\fR \fBCodeRef|Ref|Str|Undef\fR" 4
.IX Item "default CodeRef|Ref|Str|Undef"
A default may be provided for a parameter.
.Sp
.Vb 5
\& state $check = compile(
\&   Int,
\&   Int, { default => "666" },
\&   Int, { default => "999" },
\& );
.Ve
.Sp
Supported defaults are any strings (including numerical ones), \f(CW\*(C`undef\*(C'\fR,
and empty hashrefs and arrayrefs. Non-empty hashrefs and arrayrefs are
\&\fInot allowed as defaults\fR.
.Sp
Alternatively, you may provide a coderef to generate a default value:
.Sp
.Vb 5
\& state $check = compile(
\&   Int,
\&   Int, { default => sub { 6 * 111 } },
\&   Int, { default => sub { 9 * 111 } },
\& );
.Ve
.Sp
That coderef may generate any value, including non-empty arrayrefs and
non-empty hashrefs. For undef, simple strings, numbers, and empty
structures, avoiding using a coderef will make your parameter processing
faster.
.Sp
The default \fIwill\fR be validated against the type constraint, and
potentially coerced.
.Sp
Note that having any defaults in a specification, even if they're not
used in a particular check, will slightly slow down \f(CW$check\fR
because it means that \f(CW$check\fR can't just check \f(CW@_\fR and return
it unaltered if it's valid — it needs to build a new array to return.
.PP
As a special case, the numbers 0 and 1 may be used as shortcuts for
\&\fBOptional[Any]\fR and \fBAny\fR.
.PP
.Vb 3
\& # Positional parameters
\& state $check = compile(1, 0, 0);
\& my ($foo, $bar, $baz) = $check\->(@_);  # $bar and $baz are optional
.Ve
.PP
After any required and optional parameters may be a slurpy parameter.
Any additional arguments passed to \f(CW$check\fR will be slurped into
an arrayref or hashref and checked against the slurpy parameter.
Defaults are not supported for slurpy parameters.
.PP
Example with a slurpy ArrayRef:
.PP
.Vb 4
\& sub xyz {
\&   state $check = compile(Int, Int, slurpy ArrayRef[Int]);
\&   my ($foo, $bar, $baz) = $check\->(@_);
\& }
\& 
\& xyz(1..5);  # $foo = 1
\&             # $bar = 2
\&             # $baz = [ 3, 4, 5 ]
.Ve
.PP
Example with a slurpy HashRef:
.PP
.Vb 5
\& my $check = compile(
\&   Int,
\&   Optional[Str],
\&   slurpy HashRef[Int],
\& );
\& 
\& my ($x, $y, $z) = $check\->(1, "y", foo => 666, bar => 999);
\& # $x is 1
\& # $y is "y"
\& # $z is { foo => 666, bar => 999 }
.Ve
.PP
Any type constraints derived from \fBArrayRef\fR or \fBHashRef\fR should work,
but a type does need to inherit from one of those because otherwise
Type::Params cannot know what kind of structure to slurp the remaining
arguments into.
.PP
\&\fBslurpy Any\fR is also allowed as a special case, and is treated as
\&\fBslurpy ArrayRef\fR.
.PP
From Type::Params 1.005000 onwards, slurpy hashrefs can be passed in as a
true hashref (which will be shallow cloned) rather than key-value pairs.
.PP
.Vb 5
\& sub xyz {
\&   state $check = compile(Int, slurpy HashRef);
\&   my ($num, $hr) = $check\->(@_);
\&   ...
\& }
\& 
\& xyz( 5,   foo => 1, bar => 2   );   # works
\& xyz( 5, { foo => 1, bar => 2 } );   # works from 1.005000
.Ve
.PP
This feature is only implemented for slurpy hashrefs, not slurpy arrayrefs.
.PP
Note that having a slurpy parameter will slightly slow down \f(CW$check\fR
because it means that \f(CW$check\fR can't just check \f(CW@_\fR and return
it unaltered if it's valid — it needs to build a new array to return.
.PP
\fI\f(CI\*(C`validate(\e@_, @spec)\*(C'\fI\fR
.IX Subsection "validate(@_, @spec)"
.PP
This example of \f(CW\*(C`compile\*(C'\fR:
.PP
.Vb 5
\& sub foo {
\&   state $check = compile(@spec);
\&   my @args = $check\->(@_);
\&   ...;
\& }
.Ve
.PP
Can be written using \f(CW\*(C`validate\*(C'\fR as:
.PP
.Vb 4
\& sub foo {
\&   my @args = validate(\e@_, @spec);
\&   ...;
\& }
.Ve
.PP
Performance using \f(CW\*(C`compile\*(C'\fR will \fIalways\fR beat \f(CW\*(C`validate\*(C'\fR though.
.PP
\fI\f(CI\*(C`compile_named(@spec)\*(C'\fI\fR
.IX Subsection "compile_named(@spec)"
.PP
\&\f(CW\*(C`compile_named\*(C'\fR is a variant of \f(CW\*(C`compile\*(C'\fR for named parameters instead
of positional parameters.
.PP
The format of the specification is changed to include names for each
parameter:
.PP
.Vb 8
\& state $check = compile_named(
\&   \e%general_opts,
\&   foo   => $type_for_foo, \e%opts_for_foo,
\&   bar   => $type_for_bar, \e%opts_for_bar,
\&   baz   => $type_for_baz, \e%opts_for_baz,
\&   ...,
\&   extra => slurpy($slurpy_type),
\& );
.Ve
.PP
The \f(CW$check\fR coderef will return a hashref.
.PP
.Vb 4
\& my $check = compile_named(
\&   foo => Int,
\&   bar => Str, { default => "hello" },
\& );
\& 
\& my $args = $check\->(foo => 42);
\& # $args\->{foo} is 42
\& # $args\->{bar} is "hello"
.Ve
.PP
The \f(CW%general_opts\fR hash supports the same options as \f(CW\*(C`compile\*(C'\fR
plus a few additional options:
.ie n .IP """class"" \fBClassName\fR" 4
.el .IP "\f(CWclass\fR \fBClassName\fR" 4
.IX Item "class ClassName"
The check coderef will, instead of returning a simple hashref, call
\&\f(CW\*(C`$class\->new($hashref)\*(C'\fR and return the result.
.ie n .IP """constructor"" \fBStr\fR" 4
.el .IP "\f(CWconstructor\fR \fBStr\fR" 4
.IX Item "constructor Str"
Specifies an alternative method name instead of \f(CW\*(C`new\*(C'\fR for the \f(CW\*(C`class\*(C'\fR
option described above.
.ie n .IP """class"" \fBTuple[ClassName, Str]\fR" 4
.el .IP "\f(CWclass\fR \fBTuple[ClassName, Str]\fR" 4
.IX Item "class Tuple[ClassName, Str]"
Shortcut for declaring both the \f(CW\*(C`class\*(C'\fR and \f(CW\*(C`constructor\*(C'\fR options at once.
.ie n .IP """bless"" \fBClassName\fR" 4
.el .IP "\f(CWbless\fR \fBClassName\fR" 4
.IX Item "bless ClassName"
Like \f(CW\*(C`class\*(C'\fR, but bypass the constructor and directly bless the hashref.
.ie n .IP """named_to_list"" \fBBool\fR" 4
.el .IP "\f(CWnamed_to_list\fR \fBBool\fR" 4
.IX Item "named_to_list Bool"
Instead of returning a hashref, return a hash slice.
.Sp
.Vb 1
\& myfunc(bar => "x", foo => "y");
\& 
\& sub myfunc {
\&    state $check = compile_named(
\&       { named_to_list => 1 },
\&       foo => Str, { optional => 1 },
\&       bar => Str, { optional => 1 },
\&    );
\&    my ($foo, $bar) = $check\->(@_);
\&    ...; ## $foo is "y" and $bar is "x"
\& }
.Ve
.Sp
The order of keys for the hash slice is the same as the order of the names
passed to \f(CW\*(C`compile_named\*(C'\fR. For missing named parameters, \f(CW\*(C`undef\*(C'\fR is
returned in the list.
.Sp
Basically in the above example, \f(CW\*(C`myfunc\*(C'\fR takes named parameters, but
receieves positional parameters.
.ie n .IP """named_to_list"" \fBArrayRef[Str]\fR" 4
.el .IP "\f(CWnamed_to_list\fR \fBArrayRef[Str]\fR" 4
.IX Item "named_to_list ArrayRef[Str]"
As above, but explicitly specify the keys of the hash slice.
.PP
Like \f(CW\*(C`compile\*(C'\fR, the numbers 0 and 1 may be used as shortcuts for
\&\fBOptional[Any]\fR and \fBAny\fR.
.PP
.Vb 2
\& state $check = compile_named(foo => 1, bar => 0, baz => 0);
\& my $args = $check\->(@_);  # $args\->{bar} and $args\->{baz} are optional
.Ve
.PP
Slurpy parameters are slurped into a nested hashref.
.PP
.Vb 6
\&  my $check = compile(
\&    foo    => Str,
\&    bar    => Optional[Str],
\&    extra  => slurpy HashRef[Str],
\&  );
\&  my $args = $check\->(foo => "aaa", quux => "bbb");
\&  
\&  print $args\->{foo}, "\en";             # aaa
\&  print $args\->{extra}{quux}, "\en";     # bbb
.Ve
.PP
\&\fBslurpy Any\fR is treated as \fBslurpy HashRef\fR.
.PP
The \f(CW\*(C`head\*(C'\fR and \f(CW\*(C`tail\*(C'\fR options are supported. This allows for a
mixture of positional and named arguments, as long as the positional
arguments are non-optional and at the head and tail of \f(CW@_\fR.
.PP
.Vb 6
\&  my $check = compile(
\&    { head => [ Int, Int ], tail => [ CodeRef ] },
\&    foo => Str,
\&    bar => Str,
\&    baz => Str,
\&  );
\&  
\&  my ($int1, $int2, $args, $coderef)
\&    = $check\->( 666, 999, foo=>\*(Aqx\*(Aq, bar=>\*(Aqy\*(Aq, baz=>\*(Aqz\*(Aq, sub {...} );
\&  
\&  say $args\->{bar};  # \*(Aqy\*(Aq
.Ve
.PP
This can be combined with \f(CW\*(C`named_to_list\*(C'\fR:
.PP
.Vb 6
\&  my $check = compile(
\&    { head => [ Int, Int ], tail => [ CodeRef ], named_to_list => 1 },
\&    foo => Str,
\&    bar => Str,
\&    baz => Str,
\&  );
\&  
\&  my ($int1, $int2, $foo, $bar, $baz, $coderef)
\&    = $check\->( 666, 999, foo=>\*(Aqx\*(Aq, bar=>\*(Aqy\*(Aq, baz=>\*(Aqz\*(Aq, sub {...} );
\&  
\&  say $bar;  # \*(Aqy\*(Aq
.Ve
.PP
\fI\f(CI\*(C`validate_named(\e@_, @spec)\*(C'\fI\fR
.IX Subsection "validate_named(@_, @spec)"
.PP
Like \f(CW\*(C`compile\*(C'\fR has \f(CW\*(C`validate\*(C'\fR, \f(CW\*(C`compile_named\*(C'\fR has \f(CW\*(C`validate_named\*(C'\fR.
Just like \f(CW\*(C`validate\*(C'\fR, it's the slower way to do things, so stick with
\&\f(CW\*(C`compile_named\*(C'\fR.
.PP
\fI\f(CI\*(C`compile_named_oo(@spec)\*(C'\fI\fR
.IX Subsection "compile_named_oo(@spec)"
.PP
Here's a quick example function:
.PP
.Vb 7
\&   sub add_contact_to_database {
\&      state $check = compile_named(
\&         dbh     => Object,
\&         id      => Int,
\&         name    => Str,
\&      );
\&      my $arg = $check\->(@_);
\&      
\&      my $sth = $arg\->{db}\->prepare(\*(AqINSERT INTO contacts VALUES (?, ?)\*(Aq);
\&      $sth\->execute($arg\->{id}, $arg\->{name});
\&   }
.Ve
.PP
Looks simple, right? Did you spot that it will always die with an error
message \fICan't call method \*(L"prepare\*(R" on an undefined value\fR?
.PP
This is because we defined a parameter called 'dbh' but later tried to
refer to it as \f(CW$arg{db}\fR. Here, Perl gives us a pretty clear
error, but sometimes the failures will be far more subtle. Wouldn't it
be nice if instead we could do this?
.PP
.Vb 7
\&   sub add_contact_to_database {
\&      state $check = compile_named_oo(
\&         dbh     => Object,
\&         id      => Int,
\&         name    => Str,
\&      );
\&      my $arg = $check\->(@_);
\&      
\&      my $sth = $arg\->dbh\->prepare(\*(AqINSERT INTO contacts VALUES (?, ?)\*(Aq);
\&      $sth\->execute($arg\->id, $arg\->name);
\&   }
.Ve
.PP
If we tried to call \f(CW\*(C`$arg\->db\*(C'\fR, it would fail because there was
no such method.
.PP
Well, that's exactly what \f(CW\*(C`compile_named_oo\*(C'\fR does.
.PP
As well as giving you nice protection against mistyped parameter names,
It also looks kinda pretty, I think. Hash lookups are a little faster
than method calls, of course (though Type::Params creates the methods
using Class::XSAccessor if it's installed, so they're still pretty
fast).
.PP
An optional parameter \f(CW\*(C`foo\*(C'\fR will also get a nifty \f(CW\*(C`$arg\->has_foo\*(C'\fR
predicate method. Yay!
.PP
\&\f(CW\*(C`compile_named_oo\*(C'\fR gives you some extra options for parameters.
.PP
.Vb 7
\&   sub add_contact_to_database {
\&      state $check = compile_named_oo(
\&         dbh     => Object,
\&         id      => Int,    { default => \*(Aq0\*(Aq, getter => \*(Aqidentifier\*(Aq },
\&         name    => Str,    { optional => 1, predicate => \*(Aqhas_name\*(Aq },
\&      );
\&      my $arg = $check\->(@_);
\&      
\&      my $sth = $arg\->dbh\->prepare(\*(AqINSERT INTO contacts VALUES (?, ?)\*(Aq);
\&      $sth\->execute($arg\->identifier, $arg\->name) if $arg\->has_name;
\&   }
.Ve
.ie n .IP """getter"" \fBStr\fR" 4
.el .IP "\f(CWgetter\fR \fBStr\fR" 4
.IX Item "getter Str"
The \f(CW\*(C`getter\*(C'\fR option lets you choose the method name for getting the
argument value.
.ie n .IP """predicate"" \fBStr\fR" 4
.el .IP "\f(CWpredicate\fR \fBStr\fR" 4
.IX Item "predicate Str"
The \f(CW\*(C`predicate\*(C'\fR option lets you choose the method name for checking
the existence of an argument. By setting an explicit predicate method
name, you can force a predicate method to be generated for non-optional
arguments.
.PP
The objects returned by \f(CW\*(C`compile_named_oo\*(C'\fR are blessed into lightweight
classes which have been generated on the fly. Don't expect the names of
the classes to be stable or predictable. It's probably a bad idea to be
checking \f(CW\*(C`can\*(C'\fR, \f(CW\*(C`isa\*(C'\fR, or \f(CW\*(C`DOES\*(C'\fR on any of these objects. If you're
doing that, you've missed the point of them.
.PP
They don't have any constructor (\f(CW\*(C`new\*(C'\fR method). The \f(CW$check\fR
coderef effectively \fIis\fR the constructor.
.PP
\fI\f(CI\*(C`validate_named_oo(\e@_, @spec)\*(C'\fI\fR
.IX Subsection "validate_named_oo(@_, @spec)"
.PP
This function doesn't even exist. :D
.PP
\fI\f(CI\*(C`multisig(@alternatives)\*(C'\fI\fR
.IX Subsection "multisig(@alternatives)"
.PP
Type::Params can export a \f(CW\*(C`multisig\*(C'\fR function that compiles multiple
alternative signatures into one, and uses the first one that works:
.PP
.Vb 5
\&   state $check = multisig(
\&      [ Int, ArrayRef ],
\&      [ HashRef, Num ],
\&      [ CodeRef ],
\&   );
\&   
\&   my ($int, $arrayref) = $check\->( 1, [] );      # okay
\&   my ($hashref, $num)  = $check\->( {}, 1.1 );    # okay
\&   my ($code)           = $check\->( sub { 1 } );  # okay
\&   
\&   $check\->( sub { 1 }, 1.1 );  # throws an exception
.Ve
.PP
Coercions, slurpy parameters, etc still work.
.PP
The magic global \f(CW\*(C`${^TYPE_PARAMS_MULTISIG}\*(C'\fR is set to the index of
the first signature which succeeded.
.PP
The present implementation involves compiling each signature independently,
and trying them each (in their given order!) in an \f(CW\*(C`eval\*(C'\fR block. The only
slightly intelligent part is that it checks if \f(CW\*(C`scalar(@_)\*(C'\fR fits into
the signature properly (taking into account optional and slurpy parameters),
and skips evals which couldn't possibly succeed.
.PP
It's also possible to list coderefs as alternatives in \f(CW\*(C`multisig\*(C'\fR:
.PP
.Vb 7
\&   state $check = multisig(
\&      [ Int, ArrayRef ],
\&      sub { ... },
\&      [ HashRef, Num ],
\&      [ CodeRef ],
\&      compile_named( needle => Value, haystack => Ref ),
\&   );
.Ve
.PP
The coderef is expected to die if that alternative should be abandoned (and
the next alternative tried), or return the list of accepted parameters. Here's
a full example:
.PP
.Vb 11
\&   sub get_from {
\&      state $check = multisig(
\&         [ Int, ArrayRef ],
\&         [ Str, HashRef ],
\&         sub {
\&            my ($meth, $obj);
\&            die unless is_Object($obj);
\&            die unless $obj\->can($meth);
\&            return ($meth, $obj);
\&         },
\&      );
\&      
\&      my ($needle, $haystack) = $check\->(@_);
\&      
\&      for (${^TYPE_PARAMS_MULTISIG}) {
\&         return $haystack\->[$needle] if $_ == 0;
\&         return $haystack\->{$needle} if $_ == 1;
\&         return $haystack\->$needle   if $_ == 2;
\&      }
\&   }
\&   
\&   get_from(0, \e@array);      # returns $array[0]
\&   get_from(\*(Aqfoo\*(Aq, \e%hash);   # returns $hash{foo}
\&   get_from(\*(Aqfoo\*(Aq, $obj);     # returns $obj\->foo
.Ve
.PP
The default error message is just \f(CW"Parameter validation failed"\fR.
You can pass an option hashref as the first argument with an informative
message string:
.PP
.Vb 11
\&   sub foo {
\&      state $OptionsDict = Dict[...];
\&      state $check = multisig(
\&         { message => \*(AqUSAGE: $object\->foo(\e%options?, $string)\*(Aq },
\&         [ Object, $OptionsDict, StringLike ],
\&         [ Object, StringLike ],
\&      );
\&      my ($self, @args) = $check\->(@_);
\&      my ($opts, $str)  = ${^TYPE_PARAMS_MULTISIG} ? ({}, @args) : @_;
\&      ...;
\&   }
\&   
\&   $obj\->foo(\e%opts, "Hello");
\&   $obj\->foo("World");
.Ve
.PP
\fI\f(CI\*(C`wrap_subs( $subname1, $wrapper1, ... )\*(C'\fI\fR
.IX Subsection "wrap_subs( $subname1, $wrapper1, ... )"
.PP
It's possible to turn the check inside-out and instead of the sub calling
the check, the check can call the original sub.
.PP
Normal way:
.PP
.Vb 2
\&   use Type::Param qw(compile);
\&   use Types::Standard qw(Int Str);
\&   
\&   sub foobar {
\&      state $check = compile(Int, Str);
\&      my ($foo, $bar) = @_;
\&      ...;
\&   }
.Ve
.PP
Inside-out way:
.PP
.Vb 2
\&   use Type::Param qw(wrap_subs);
\&   use Types::Standard qw(Int Str);
\&   
\&   sub foobar {
\&      my ($foo, $bar) = @_;
\&      ...;
\&   }
\&   
\&   wrap_subs foobar => [Int, Str];
.Ve
.PP
\&\f(CW\*(C`wrap_subs\*(C'\fR takes a hash of subs to wrap. The keys are the sub names and the
values are either arrayrefs of arguments to pass to \f(CW\*(C`compile\*(C'\fR to make a check,
or coderefs that have already been built by \f(CW\*(C`compile\*(C'\fR, \f(CW\*(C`compile_named\*(C'\fR, or
\&\f(CW\*(C`compile_named_oo\*(C'\fR.
.PP
\fI\f(CI\*(C`wrap_methods( $subname1, $wrapper1, ... )\*(C'\fI\fR
.IX Subsection "wrap_methods( $subname1, $wrapper1, ... )"
.PP
\&\f(CW\*(C`wrap_methods\*(C'\fR also exists, which shifts off the invocant from \f(CW@_\fR
before the check, but unshifts it before calling the original sub.
.PP
.Vb 2
\&   use Type::Param qw(wrap_subs);
\&   use Types::Standard qw(Int Str);
\&   
\&   sub foobar {
\&      my ($self, $foo, $bar) = @_;
\&      ...;
\&   }
\&   
\&   wrap_subs foobar => [Int, Str];
.Ve
.PP
\fI\f(BIInvocant\fI\fR
.IX Subsection "Invocant"
.PP
Type::Params exports a type \fBInvocant\fR on request. This gives you a type
constraint which accepts classnames \fIand\fR blessed objects.
.PP
.Vb 1
\& use Type::Params qw( compile Invocant );
\& 
\& sub my_method {
\&   state $check = compile(Invocant, ArrayRef, Int);
\&   my ($self_or_class, $arr, $ix) = $check\->(@_);
\&   
\&   return $arr\->[ $ix ];
\& }
.Ve
.PP
\fI\f(BIArgsObject\fI\fR
.IX Subsection "ArgsObject"
.PP
Type::Params exports a parameterizable type constraint \fBArgsObject\fR.
It accepts the kinds of objects returned by \f(CW\*(C`compile_named_oo\*(C'\fR checks.
.PP
.Vb 3
\&  package Foo {
\&    use Moo;
\&    use Type::Params \*(AqArgsObject\*(Aq;
\&    
\&    has args => (
\&      is  => \*(Aqro\*(Aq,
\&      isa => ArgsObject[\*(AqBar::bar\*(Aq],
\&    );
\&  }
\&  
\&  package Bar {
\&    use Types::Standard \-types;
\&    use Type::Params \*(Aqcompile_named_oo\*(Aq;
\&    
\&    sub bar {
\&      state $check = compile_named_oo(
\&        xxx => Int,
\&        yyy => ArrayRef,
\&      );
\&      my $args = &$check;
\&      
\&      return \*(AqFoo\*(Aq\->new( args => $args );
\&    }
\&  }
\&  
\&  Bar::bar( xxx => 42, yyy => [] );
.Ve
.PP
The parameter \*(L"Bar::bar\*(R" refers to the caller when the check is compiled,
rather than when the parameters are checked.
.SH "ENVIRONMENT"
.IX Header "ENVIRONMENT"
.ie n .IP """PERL_TYPE_PARAMS_XS""" 4
.el .IP "\f(CWPERL_TYPE_PARAMS_XS\fR" 4
.IX Item "PERL_TYPE_PARAMS_XS"
Affects the building of accessors for \f(CW\*(C`compile_named_oo\*(C'\fR. If set to true,
will use Class::XSAccessor. If set to false, will use pure Perl. If this
environment variable does not exist, will use Class::XSAccessor if it
is available.
.SH "BUGS"
.IX Header "BUGS"
Please report any bugs to
<https://github.com/tobyink/p5\-type\-tiny/issues>.
.SH "SEE ALSO"
.IX Header "SEE ALSO"
The Type::Tiny homepage <https://typetiny.toby.ink/>.
.PP
Type::Tiny, Type::Coercion, Types::Standard.
.SH "AUTHOR"
.IX Header "AUTHOR"
Toby Inkster <tobyink@cpan.org>.
.SH "COPYRIGHT AND LICENCE"
.IX Header "COPYRIGHT AND LICENCE"
This software is copyright (c) 2013\-2014, 2017\-2021 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