.\" Automatically generated by Pod::Man 2.28 (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 3pm" .TH Type::Params 3pm "2014-10-25" "perl v5.20.1" "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) = $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 "COOKBOOK" .IX Header "COOKBOOK" .SS "Positional Parameters" .IX Subsection "Positional Parameters" .Vb 4 \& sub nth_root \& { \& state $check = compile( Num, Num ); \& my ($x, $n) = $check\->(@_); \& \& return $x ** (1 / $n); \& } .Ve .SS "Method Calls" .IX Subsection "Method Calls" Type::Params exports an additional keyword \f(CW\*(C`Invocant\*(C'\fR on request. This is a type constraint accepting blessed objects and also class names. .PP .Vb 2 \& use Types::Standard qw( ClassName Object Str Int ); \& use Type::Params qw( compile Invocant ); \& \& # a class method \& sub new_from_json \& { \& state $check = compile( ClassName, Str ); \& my ($class, $json) = $check\->(@_); \& \& $class\->new( from_json($json) ); \& } \& \& # an object method \& sub dump \& { \& state $check = compile( Object, Int ); \& my ($self, $limit) = $check\->(@_); \& \& local $Data::Dumper::Maxdepth = $limit; \& print Data::Dumper::Dumper($self); \& } \& \& # can be called as either and object or class method \& sub run \& { \& state $check = compile( Invocant ); \& my ($proto) = $check\->(@_); \& \& my $self = ref($proto) ? $proto : $default_instance; \& $self\->_run; \& } .Ve .SS "Optional Parameters" .IX Subsection "Optional Parameters" .Vb 1 \& use Types::Standard qw( Object Optional Int ); \& \& sub dump \& { \& state $check = compile( Object, Optional[Int] ); \& my ($self, $limit) = $check\->(@_); \& $limit //= 0; \& \& local $Data::Dumper::Maxdepth = $limit; \& print Data::Dumper::Dumper($self); \& } \& \& $obj\->dump(1); # ok \& $obj\->dump(); # ok \& $obj\->dump(undef); # dies .Ve .SS "Slurpy Parameters" .IX Subsection "Slurpy Parameters" .Vb 1 \& use Types::Standard qw( slurpy ClassName HashRef ); \& \& sub new \& { \& state $check = compile( ClassName, slurpy HashRef ); \& my ($class, $ref) = $check\->(@_); \& bless $ref => $class; \& } \& \& _\|_PACKAGE_\|_\->new(foo => 1, bar => 2); .Ve .PP The following types from Types::Standard can be made slurpy: \&\f(CW\*(C`ArrayRef\*(C'\fR, \f(CW\*(C`Tuple\*(C'\fR, \f(CW\*(C`HashRef\*(C'\fR, \f(CW\*(C`Map\*(C'\fR, \f(CW\*(C`Dict\*(C'\fR. Hash-like types will die if an odd number of elements are slurped in. .PP A check may only have one slurpy parameter, and it must be the last parameter. .SS "Named Parameters" .IX Subsection "Named Parameters" Just use a slurpy \f(CW\*(C`Dict\*(C'\fR: .PP .Vb 1 \& use Types::Standard qw( slurpy Dict Ref Optional Int ); \& \& sub dump \& { \& state $check = compile( \& slurpy Dict[ \& var => Ref, \& limit => Optional[Int], \& ], \& ); \& my ($arg) = $check\->(@_); \& \& local $Data::Dumper::Maxdepth = $arg\->{limit}; \& print Data::Dumper::Dumper($arg\->{var}); \& } \& \& dump(var => $foo, limit => 1); # ok \& dump(var => $foo); # ok \& dump(limit => 1); # dies .Ve .SS "Mixed Positional and Named Parameters" .IX Subsection "Mixed Positional and Named Parameters" .Vb 1 \& use Types::Standard qw( slurpy Dict Ref Optional Int ); \& \& sub my_print \& { \& state $check = compile( \& Str, \& slurpy Dict[ \& colour => Optional[Str], \& size => Optional[Int], \& ], \& ); \& my ($string, $arg) = $check\->(@_); \& } \& \& my_print("Hello World", colour => "blue"); .Ve .SS "Coercions" .IX Subsection "Coercions" Coercions will automatically be applied for \fIall\fR type constraints that have a coercion associated. .PP .Vb 2 \& use Type::Utils; \& use Types::Standard qw( Int Num ); \& \& my $RoundedInt = declare as Int; \& coerce $RoundedInt, from Num, q{ int($_) }; \& \& sub set_age \& { \& state $check = compile( Object, $RoundedInt ); \& my ($self, $age) = $check\->(@_); \& \& $self\->{age} = $age; \& } \& \& $obj\->set_age(32.5); # ok; coerced to "32". .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 If type \f(CW\*(C`Foo\*(C'\fR has coercions from \f(CW\*(C`Str\*(C'\fR and \f(CW\*(C`ArrayRef\*(C'\fR and you want to \&\fBprevent\fR coercion, then use: .PP .Vb 1 \& state $check = compile( Foo\->no_coercions ); .Ve .PP Or if you just want to prevent coercion from \f(CW\*(C`Str\*(C'\fR, use: .PP .Vb 1 \& state $check = compile( Foo\->minus_coercions(Str) ); .Ve .PP Or maybe add an extra coercion: .PP .Vb 3 \& state $check = compile( \& Foo\->plus_coercions(Int, q{ Foo\->new_from_number($_) }), \& ); .Ve .PP Note that the coercion is specified as a string of Perl code. This is usually the fastest way to do it, but a coderef is also accepted. Either way, the value to be coerced is \f(CW$_\fR. .SS "Alternatives" .IX Subsection "Alternatives" 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, [] ); \& my ($hashref, $num) = $check\->( {}, 1.1 ); \& my ($code) = $check\->( sub { 1 } ); \& \& $check\->( sub { 1 }, 1.1 ); # throws an exception .Ve .PP Coercions, slurpy parameters, etc still work. .PP There's currently no indication of which of the multiple signatures 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 6 \& state $check = multisig( \& [ Int, ArrayRef ], \& sub { ... }, \& [ HashRef, Num ], \& [ CodeRef ], \& ); .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 12 \& 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\->(@_); \& \& is_HashRef($haystack) ? $haystack\->{$needle} : \& is_ArrayRef($haystack) ? $haystack\->[$needle] : \& is_Object($haystack) ? $haystack\->$needle : \& die; \& } \& \& 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 "COMPARISON WITH PARAMS::VALIDATE" .IX Header "COMPARISON WITH 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 Type::Params is mostly geared towards positional parameters, while Params::Validate seems to be primarily aimed at named parameters. (Though either works for either.) 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 Params::Validate allows you to supply defaults for missing parameters; Type::Params does not, but you may be able to use coercion from Undef. .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 "BUGS" .IX Header "BUGS" Please report any bugs to . .SH "SEE ALSO" .IX Header "SEE ALSO" Type::Tiny, Type::Coercion, Types::Standard. .SH "AUTHOR" .IX Header "AUTHOR" Toby Inkster . .SH "COPYRIGHT AND LICENCE" .IX Header "COPYRIGHT AND LICENCE" This software is copyright (c) 2013\-2014 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