%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /home/opti/perl/usr/man/man3/
Upload File :
Create Path :
Current File : /home/opti/perl/usr/man/man3/Type::Params.3pm

.\" Automatically generated by Pod::Man 2.27 (Pod::Simple 3.28)
.\"
.\" 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 turned on, 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
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear.  Run.  Save yourself.  No user-serviceable parts.
.    \" fudge factors for nroff and troff
.if n \{\
.    ds #H 0
.    ds #V .8m
.    ds #F .3m
.    ds #[ \f1
.    ds #] \fP
.\}
.if t \{\
.    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
.    ds #V .6m
.    ds #F 0
.    ds #[ \&
.    ds #] \&
.\}
.    \" simple accents for nroff and troff
.if n \{\
.    ds ' \&
.    ds ` \&
.    ds ^ \&
.    ds , \&
.    ds ~ ~
.    ds /
.\}
.if t \{\
.    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
.    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
.    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
.    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
.    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
.    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
.    \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
.    \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
.    \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
.    ds : e
.    ds 8 ss
.    ds o a
.    ds d- d\h'-1'\(ga
.    ds D- D\h'-1'\(hy
.    ds th \o'bp'
.    ds Th \o'LP'
.    ds ae ae
.    ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "Type::Params 3"
.TH Type::Params 3 "2018-07-29" "perl v5.16.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.10;
\& use strict;
\& use warnings;
\& 
\& use Type::Params qw( compile );
\& use Types::Standard qw( slurpy Str ArrayRef Num );
\&   
\& sub deposit_monies
\& {
\&    state $check = compile( Str, Str, slurpy ArrayRef[Num] );
\&    my ($sort_code, $account_number, $monies) = $check\->(@_);
\&    
\&    my $account = Local::BankAccount\->new($sort_code, $account_number);
\&    $account\->deposit($_) for @$monies;
\& }
\& 
\& deposit_monies("12\-34\-56", "11223344", 1.2, 3, 99.99);
.Ve
.SH "STATUS"
.IX Header "STATUS"
This module is covered by the
Type-Tiny stability policy.
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
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 5
\& my $deposit_monies_check;
\& sub deposit_monies
\& {
\&    $deposit_monies_check ||= compile( Str, Str, slurpy ArrayRef[Num] );
\&    my ($sort_code, $account_number, $monies) = $deposit_monies_check\->(@_);
\&    
\&    ...;
\& }
.Ve
.PP
Not quite as neat, but not awful either.
.PP
There's a shortcut reducing it to one step:
.PP
.Vb 1
\& use Type::Params qw( validate );
\& 
\& sub deposit_monies
\& {
\&    my ($sort_code, $account_number, $monies) = 
\&       validate( \e@_, Str, Str, slurpy ArrayRef[Num] );
\&    
\&    ...;
\& }
.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.
.SH "VALIDATE VERSUS COMPILE"
.IX Header "VALIDATE VERSUS COMPILE"
This module offers one-stage (\*(L"validate\*(R") and two-stage (\*(L"compile\*(R" then
\&\*(L"check\*(R") variants of parameter checking for you to use. Performance with
the two-stage variant will \fIalways\fR beat the one stage variant X I
cannot think of many reasons you'd want to use the one-stage version.
.PP
.Vb 2
\& # One\-stage, positional parameters
\& my @args = validate(\e@_, @spec);
\& 
\& # Two\-stage, positional parameters
\& state $check = compile(@spec);
\& my @args = $check\->(@_);
\& 
\& # One\-stage, named parameters
\& my $args = validate_named(\e@_, @spec);
\& 
\& # Two\-stage, named parameters
\& state $check = compile_named(@spec);
\& my $args = $check\->(@_);
.Ve
.PP
Use \f(CW\*(C`compile\*(C'\fR and \f(CW\*(C`compile_named\*(C'\fR, not \f(CW\*(C`validate\*(C'\fR and \f(CW\*(C`validate_named\*(C'\fR.
.SH "VALIDATION SPECIFICATIONS"
.IX Header "VALIDATION SPECIFICATIONS"
The \f(CW@spec\fR is where most of the magic happens.
.PP
The generalized form of specifications for positional parameters is:
.PP
.Vb 8
\& @spec = (
\&   \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
And for named parameters:
.PP
.Vb 8
\& @spec = (
\&   \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,
\&   ...,
\&   slurpy($slurpy_type),
\& );
.Ve
.PP
Option hashrefs can simply be omitted if you don't need to specify any
particular options.
.PP
The \f(CW\*(C`slurpy\*(C'\fR function is exported by Types::Standard. It may be
omitted if not needed.
.SS "General Options"
.IX Subsection "General Options"
Currently supported general options are:
.ie n .IP """want_source => Bool""" 4
.el .IP "\f(CWwant_source => Bool\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 => Bool""" 4
.el .IP "\f(CWwant_details => Bool\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 """class => ClassName""" 4
.el .IP "\f(CWclass => ClassName\fR" 4
.IX Item "class => ClassName"
\&\fBNamed parameters only.\fR The check coderef will, instead of returning
a simple hashref, call \f(CW\*(C`$class\->new($hashref)\*(C'\fR and return a proper
object.
.ie n .IP """constructor => Str""" 4
.el .IP "\f(CWconstructor => Str\fR" 4
.IX Item "constructor => Str"
\&\fBNamed parameters only.\fR Specify 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 => Tuple[ClassName, Str]""" 4
.el .IP "\f(CWclass => Tuple[ClassName, Str]\fR" 4
.IX Item "class => Tuple[ClassName, Str]"
\&\fBNamed parameters only.\fR Given a class name and constructor name pair,
the check coderef will, instead of returning a simple hashref, call
\&\f(CW\*(C`$class\->$constructor($hashref)\*(C'\fR and return a proper object. 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 => ClassName""" 4
.el .IP "\f(CWbless => ClassName\fR" 4
.IX Item "bless => ClassName"
\&\fBNamed parameters only.\fR Bypass the constructor entirely and directly
bless the hashref.
.ie n .IP """description => Str""" 4
.el .IP "\f(CWdescription => Str\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 => Str""" 4
.el .IP "\f(CWsubname => Str\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 => Int""" 4
.el .IP "\f(CWcaller_level => Int\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.
.SS "Type Constraints"
.IX Subsection "Type Constraints"
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.
.SS "Optional Parameters"
.IX Subsection "Optional Parameters"
The \f(CW\*(C`Optional\*(C'\fR parameterizable type constraint from Types::Standard
may be used to indicate optional parameters.
.PP
.Vb 3
\& # Positional parameters
\& state $check = compile(Int, Optional[Int], Optional[Int]);
\& my ($foo, $bar, $baz) = $check\->(@_);  # $bar and $baz are optional
\& 
\& # Named parameters
\& state $check = compile(
\&   foo => Int,
\&   bar => Optional[Int],
\&   baz => Optional[Int],
\& );
\& my $args = $check\->(@_);  # $args\->{bar} and $args\->{baz} are optional
.Ve
.PP
As a special case, the numbers 0 and 1 may be used as shortcuts for
\&\f(CW\*(C`Optional[Any]\*(C'\fR and \f(CW\*(C`Any\*(C'\fR.
.PP
.Vb 3
\& # Positional parameters
\& state $check = compile(1, 0, 0);
\& my ($foo, $bar, $baz) = $check\->(@_);  # $bar and $baz are optional
\& 
\& # Named parameters
\& state $check = compile_named(foo => 1, bar => 0, baz => 0);
\& my $args = $check\->(@_);  # $args\->{bar} and $args\->{baz} are optional
.Ve
.PP
If you're using positional parameters, then required parameters must
precede any optional ones.
.SS "Slurpy Parameters"
.IX Subsection "Slurpy Parameters"
Specifications may include a single slurpy parameter which should have
a type constraint derived from \f(CW\*(C`ArrayRef\*(C'\fR or \f(CW\*(C`HashRef\*(C'\fR. (\f(CW\*(C`Any\*(C'\fR is
also allowed, which is interpreted as \f(CW\*(C`ArrayRef\*(C'\fR in the case of positional
parameters, and \f(CW\*(C`HashRef\*(C'\fR in the case of named parameters.)
.PP
If a slurpy parameter is provided in the specification, the \f(CW$check\fR
coderef will slurp up any remaining arguments from \f(CW@_\fR (after
required and optional parameters have been removed), validate it against
the given slurpy type, and return it as a single arrayref/hashref.
.PP
For example:
.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
A specification have one or zero slurpy parameters. If there is a slurpy
parameter, it must be the final one.
.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 X it needs to build a new array to return.
.SS "Type Coercion"
.IX Subsection "Type Coercion"
Type coercions are automatically applied for all types that have
coercions.
.PP
.Vb 1
\& my $RoundedInt = Int\->plus_coercions(Num, q{ int($_) });
\& 
\& state $check = compile($RoundedInt, $RoundedInt);
\& my ($foo, $bar) = $check\->(@_);
\& 
\& # if @_ is (1.1, 2.2), then $foo is 1 and $bar is 2.
.Ve
.PP
Coercions carry over into structured types such as \f(CW\*(C`ArrayRef\*(C'\fR automatically:
.PP
.Vb 4
\& sub delete_articles
\& {
\&   state $check = compile( Object, slurpy ArrayRef[$RoundedInt] );
\&   my ($db, $articles) = $check\->(@_);
\&   
\&   $db\->select_article($_)\->delete for @$articles;
\& }
\& 
\& # delete articles 1, 2 and 3
\& delete_articles($my_db, 1.1, 2.2, 3.3);
.Ve
.PP
That's a Types::Standard feature rather than something specific to
Type::Params.
.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 X it needs to build a new array to return.
.SS "Parameter Options"
.IX Subsection "Parameter Options"
The type constraint for a parameter may be followed by a hashref of
options for it.
.PP
The following options are supported:
.ie n .IP """optional => Bool""" 4
.el .IP "\f(CWoptional => Bool\fR" 4
.IX Item "optional => Bool"
This is an alternative way of indicating that a parameter is optional.
.Sp
.Vb 5
\& state $check = compile_named(
\&   foo => Int,
\&   bar => Int, { optional => 1 },
\&   baz => Optional[Int],
\& );
.Ve
.Sp
The two are not \fIexactly\fR equivalent. If you were to set \f(CW\*(C`bar\*(C'\fR to a
non-integer, it would throw an exception about the \f(CW\*(C`Int\*(C'\fR type constraint
being violated. If \f(CW\*(C`baz\*(C'\fR were a non-integer, the exception would mention
the \f(CW\*(C`Optional[Int]\*(C'\fR type constraint instead.
.ie n .IP """default => CodeRef|Ref|Str|Undef""" 4
.el .IP "\f(CWdefault => CodeRef|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_named(
\&   foo => Int,
\&   bar => Int, { default => "666" },
\&   baz => 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_named(
\&   foo => Int,
\&   bar => Int, { default => sub { 6 * 111 } },
\&   baz => 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
Defaults are not supported for slurpy parameters.
.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 X it needs to build a new array to return.
.SH "MULTIPLE SIGNATURES"
.IX Header "MULTIPLE SIGNATURES"
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
.SH "PARAMETER OBJECTS"
.IX Header "PARAMETER OBJECTS"
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!
.SS "Options"
.IX Subsection "Options"
\&\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
.PP
The \f(CW\*(C`getter\*(C'\fR option lets you choose the method name for getting the
argument value. The \f(CW\*(C`predicate\*(C'\fR option lets you choose the method name
for checking the existence of an argument.
.PP
By setting an explicit predicate method name, you can force a predicate
method to be generated for non-optional arguments.
.SS "Classes"
.IX Subsection "Classes"
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.
.SH "COOKBOOK"
.IX Header "COOKBOOK"
.SS "Mixed Positional and Named Parameters"
.IX Subsection "Mixed Positional and Named Parameters"
This can be faked using positional parameters and a slurpy dictionary.
.PP
.Vb 8
\& state $check = compile(
\&   Int,
\&   slurpy Dict[
\&     foo => Int,
\&     bar => Optional[Int],
\&     baz => Optional[Int],
\&   ],
\& );
\& 
\& @_ = (42, foo => 21);                 # ok
\& @_ = (42, foo => 21, bar  => 84);     # ok
\& @_ = (42, foo => 21, bar  => 10.5);   # not ok
\& @_ = (42, foo => 21, quux => 84);     # not ok
.Ve
.SS "Method Calls"
.IX Subsection "Method Calls"
Some people like to \f(CW\*(C`shift\*(C'\fR off the invocant before running type checks:
.PP
.Vb 7
\& sub my_method {
\&   my $self = shift;
\&   state $check = compile_named(
\&     haystack => ArrayRef,
\&     needle   => Int,
\&   );
\&   my $arg = $check\->(@_);
\&   
\&   return $arg\->{haystack}[ $self\->base_index + $arg\->{needle} ];
\& }
\& 
\& $object\->my_method(haystack => \e@somelist, needle => 42);
.Ve
.PP
If you're using positional parameters, there's really no harm in including
the invocant in the check:
.PP
.Vb 3
\& sub my_method {
\&   state $check = compile(Object, ArrayRef, Int);
\&   my ($self, $arr, $ix) = $check\->(@_);
\&   
\&   return $arr\->[ $self\->base_index + $ix ];
\& }
\& 
\& $object\->my_method(\e@somelist, 42);
.Ve
.PP
Some methods will be designed to be called as class methods rather than
instance methods. Remember to use \f(CW\*(C`ClassName\*(C'\fR instead of \f(CW\*(C`Object\*(C'\fR in
those cases.
.PP
Type::Params exports an additional keyword \f(CW\*(C`Invocant\*(C'\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(Instance, ArrayRef, Int);
\&   my ($self_or_class, $arr, $ix) = $check\->(@_);
\&   
\&   return $arr\->[ $ix ];
\& }
.Ve
.ie n .SS "There is no ""coerce => 0"""
.el .SS "There is no \f(CWcoerce => 0\fP"
.IX Subsection "There is no coerce => 0"
If you give \f(CW\*(C`compile\*(C'\fR a type constraint which has coercions, then
\&\f(CW$check\fR will \fIalways coerce\fR. It cannot be switched off.
.PP
Luckily, Type::Tiny gives you a very easy way to create a type
constraint without coercions from one that has coercions:
.PP
.Vb 4
\& state $check = compile(
\&   $RoundedInt\->no_coercions,
\&   $RoundedInt\->minus_coercions(Num),
\& );
.Ve
.PP
That's a Type::Tiny feature rather than a Type::Params feature though.
.SS "Extra Coercions"
.IX Subsection "Extra Coercions"
Type::Tiny provides an easy shortcut for adding coercions to
a type constraint:
.PP
.Vb 4
\& # We want an arrayref, but accept a hashref and coerce it
\& state $check => compile(
\&   ArrayRef\->plus_coercions( HashRef, sub { [sort values %$_] } ),
\& );
.Ve
.SS "Value Constraints"
.IX Subsection "Value Constraints"
You may further constrain a parameter using \f(CW\*(C`where\*(C'\fR:
.PP
.Vb 3
\& state $check = compile(
\&   Int\->where(\*(Aq$_ % 2 == 0\*(Aq),   # even numbers only
\& );
.Ve
.PP
This is also a Type::Tiny feature rather than a Type::Params feature.
.SS "Smarter Defaults"
.IX Subsection "Smarter Defaults"
This works:
.PP
.Vb 5
\& sub print_coloured {
\&   state $check = compile(
\&     Str,
\&     Str, { default => "black" },
\&   );
\&   
\&   my ($text, $colour) = $check\->(@_);
\&   
\&   ...;
\& }
.Ve
.PP
But so does this (and it might benchmark a little faster):
.PP
.Vb 5
\& sub print_coloured {
\&   state $check = compile(
\&     Str,
\&     Str, { optional => 1 },
\&   );
\&   
\&   my ($text, $colour) = $check\->(@_);
\&   $colour = "black" if @_ < 2;
\&   
\&   ...;
\& }
.Ve
.PP
Just because Type::Params now supports defaults, doesn't mean you can't
do it the old-fashioned way. The latter is more flexible. In the example,
we've used \f(CW\*(C`if @_ < 2\*(C'\fR, but we could instead have done something like:
.PP
.Vb 1
\&   $colour ||= "black";
.Ve
.PP
Which would have defaulted \f(CW$colour\fR to \*(L"black\*(R" if it were the empty
string.
.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 "COMPARISONS WITH OTHER MODULES"
.IX Header "COMPARISONS WITH OTHER MODULES"
.SS "Params::Validate"
.IX Subsection "Params::Validate"
Type::Params is not really a drop-in replacement for Params::Validate;
the \s-1API\s0 differs far too much to claim that. Yet it performs a similar task,
so it makes sense to compare them.
.IP "\(bu" 4
Type::Params will tend to be faster if you've got a sub which is called
repeatedly, but may be a little slower than Params::Validate for subs that
are only called a few times. This is because it does a bunch of work the
first time your sub is called to make subsequent calls a lot faster.
.IP "\(bu" 4
Params::Validate doesn't appear to have a particularly natural way of
validating a mix of positional and named parameters.
.IP "\(bu" 4
Type::Utils allows you to coerce parameters. For example, if you expect
a Path::Tiny object, you could coerce it from a string.
.IP "\(bu" 4
If you are primarily writing object-oriented code, using Moose or similar,
and you are using Type::Tiny type constraints for your attributes, then
using Type::Params allows you to use the same constraints for method calls.
.IP "\(bu" 4
Type::Params comes bundled with Types::Standard, which provides a much
richer vocabulary of types than the type validation constants that come
with Params::Validate. For example, Types::Standard provides constraints
like \f(CW\*(C`ArrayRef[Int]\*(C'\fR (an arrayref of integers), while the closest from
Params::Validate is \f(CW\*(C`ARRAYREF\*(C'\fR, which you'd need to supplement with
additional callbacks if you wanted to check that the arrayref contained
integers.
.Sp
Whatsmore, Type::Params doesn't just work with Types::Standard, but also
any other Type::Tiny type constraints.
.SH "Params::ValidationCompiler"
.IX Header "Params::ValidationCompiler"
Params::ValidationCompiler does basically the same thing as
Type::Params.
.IP "\(bu" 4
Params::ValidationCompiler and Type::Params are likely to perform fairly
similarly. In most cases, recent versions of Type::Params seem to be
\&\fIslightly\fR faster, but except in very trivial cases, you're unlikely to
notice the speed difference. Speed probably shouldn't be a factor when
choosing between them.
.IP "\(bu" 4
Type::Params's syntax is more compact:
.Sp
.Vb 1
\&   state $check = compile(Object, Optional[Int], slurpy ArrayRef);
.Ve
.Sp
Versus:
.Sp
.Vb 7
\&   state $check = validation_for(
\&      params => [
\&         { type => Object },
\&         { type => Int,      optional => 1 },
\&         { type => ArrayRef, slurpy => 1 },
\&      ],
\&   );
.Ve
.IP "\(bu" 4
Params::ValidationCompiler probably has slightly better exceptions.
.SH "BUGS"
.IX Header "BUGS"
Please report any bugs to
<http://rt.cpan.org/Dist/Display.html?Queue=Type\-Tiny>.
.SH "SEE ALSO"
.IX Header "SEE ALSO"
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\-2018 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

Zerion Mini Shell 1.0