1Type::Params(3)       User Contributed Perl Documentation      Type::Params(3)
2
3
4

NAME

6       Type::Params - Params::Validate-like parameter validation using
7       Type::Tiny type constraints and coercions
8

SYNOPSIS

10        use v5.12;
11        use strict;
12        use warnings;
13
14        package Horse {
15          use Moo;
16          use Types::Standard qw( Object );
17          use Type::Params qw( compile );
18          use namespace::autoclean;
19
20          ...;   # define attributes, etc
21
22          sub add_child {
23            state $check = compile( Object, Object );  # method signature
24
25            my ($self, $child) = $check->(@_);         # unpack @_
26            push @{ $self->children }, $child;
27
28            return $self;
29          }
30        }
31
32        package main;
33
34        my $boldruler = Horse->new;
35
36        $boldruler->add_child( Horse->new );
37
38        $boldruler->add_child( 123 );   # dies (123 is not an Object!)
39

STATUS

41       This module is covered by the Type-Tiny stability policy.
42

DESCRIPTION

44       This documents the details of the Type::Params package.
45       Type::Tiny::Manual is a better starting place if you're new.
46
47       Type::Params uses Type::Tiny constraints to validate the parameters to
48       a sub. It takes the slightly unorthodox approach of separating
49       validation into two stages:
50
51       1.  Compiling the parameter specification into a coderef; then
52
53       2.  Using the coderef to validate parameters.
54
55       The first stage is slow (it might take a couple of milliseconds), but
56       you only need to do it the first time the sub is called. The second
57       stage is fast; according to my benchmarks faster even than the XS
58       version of Params::Validate.
59
60       If you're using a modern version of Perl, you can use the "state"
61       keyword which was a feature added to Perl in 5.10. If you're stuck on
62       Perl 5.8, the example from the SYNOPSIS could be rewritten as:
63
64          my $add_child_check;
65          sub add_child {
66            $add_child_check ||= compile( Object, Object );
67
68            my ($self, $child) = $add_child_check->(@_);  # unpack @_
69            push @{ $self->children }, $child;
70
71            return $self;
72          }
73
74       Not quite as neat, but not awful either.
75
76       If you don't like the two step, there's a shortcut reducing it to one
77       step:
78
79          use Type::Params qw( validate );
80
81          sub add_child {
82            my ($self, $child) = validate(\@_, Object, Object);
83            push @{ $self->children }, $child;
84            return $self;
85          }
86
87       Type::Params has a few tricks up its sleeve to make sure performance
88       doesn't suffer too much with the shortcut, but it's never going to be
89       as fast as the two stage compile/execute.
90
91   Functions
92       "compile(@spec)"
93
94       Given specifications for positional parameters, compiles a coderef that
95       can check against them.
96
97       The generalized form of specifications for positional parameters is:
98
99        state $check = compile(
100          \%general_opts,
101          $type_for_arg_1, \%opts_for_arg_1,
102          $type_for_arg_2, \%opts_for_arg_2,
103          $type_for_arg_3, \%opts_for_arg_3,
104          ...,
105          slurpy($slurpy_type),
106        );
107
108       If a hashref of options is empty, it can simply be omitted. Much of the
109       time, you won't need to specify any options.
110
111        # In this example, we omit all the hashrefs
112        #
113        my $check = compile(
114          Str,
115          Int,
116          Optional[ArrayRef],
117        );
118
119        my ($str, $int, $arr) = $check->("Hello", 42, []);   # ok
120        my ($str, $int, $arr) = $check->("", -1);            # ok
121        my ($str, $int, $arr) = $check->("", -1, "bleh");    # dies
122
123       The coderef returned (i.e. $check) will check the arguments passed to
124       it conform to the spec (coercing them if appropriate), and return them
125       as a list if they do. If they don't, it will throw an exception.
126
127       The first hashref, before any type constraints, is for general options
128       which affect the entire compiled coderef. Currently supported general
129       options are:
130
131       "head" Int|ArrayRef[TypeTiny]
132           Parameters to shift off @_ before doing the main type check.  These
133           parameters may also be checked, and cannot be optional or slurpy.
134           They may not have defaults.
135
136             my $check = compile(
137               { head => [ Int, Int ] },
138               Str,
139               Str,
140             );
141
142             # ... is basically the same as...
143
144             my $check = compile(
145               Int,
146               Int,
147               Str,
148               Str,
149             );
150
151           A number may be given if you do not care to check types:
152
153             my $check = compile(
154               { head => 2 },
155               Str,
156               Str,
157             );
158
159             # ... is basically the same as...
160
161             my $check = compile(
162               Any,
163               Any,
164               Str,
165               Str,
166             );
167
168           This is mostly useless for "compile", but can be useful for
169           "compile_named" and "compile_named_oo".
170
171       "tail" Int|ArrayRef[TypeTiny]
172           Similar to "head", but pops parameters off the end of @_ instead.
173           This is actually useful for "compile" because it allows you to
174           sneak in some required parameters after a slurpy or optional
175           parameter.
176
177             my $check = compile(
178               { tail => [ CodeRef ] },
179               slurpy ArrayRef[Str],
180             );
181
182             my ($strings, $coderef) = $check->("foo", "bar", sub { ... });
183
184       "want_source" Bool
185           Instead of returning a coderef, return Perl source code string.
186           Handy for debugging.
187
188       "want_details" Bool
189           Instead of returning a coderef, return a hashref of stuff including
190           the coderef. This is mostly for people extending Type::Params and I
191           won't go into too many details about what else this hashref
192           contains.
193
194       "description" Str
195           Description of the coderef that will show up in stack traces.
196           Defaults to "parameter validation for X" where X is the caller sub
197           name.
198
199       "subname" Str
200           If you wish to use the default description, but need to change the
201           sub name, use this.
202
203       "caller_level" Int
204           If you wish to use the default description, but need to change the
205           caller level for detecting the sub name, use this.
206
207       The types for each parameter may be any Type::Tiny type constraint, or
208       anything that Type::Tiny knows how to coerce into a Type::Tiny type
209       constraint, such as a MooseX::Types type constraint or a coderef.
210
211       Type coercions are automatically applied for all types that have
212       coercions.
213
214       If you wish to avoid coercions for a type, use Type::Tiny's
215       "no_coercions" method.
216
217        my $check = compile(
218          Int,
219          ArrayRef->of(Bool)->no_coercions,
220        );
221
222       Note that having any coercions in a specification, even if they're not
223       used in a particular check, will slightly slow down $check because it
224       means that $check can't just check @_ and return it unaltered if it's
225       valid — it needs to build a new array to return.
226
227       Optional parameters can be given using the Optional[] type constraint.
228       In the example above, the third parameter is optional.  If it's
229       present, it's required to be an arrayref, but if it's absent, it is
230       ignored.
231
232       Optional parameters need to be after required parameters in the spec.
233
234       An alternative way to specify optional parameters is using a parameter
235       options hashref.
236
237        my $check = compile(
238          Str,
239          Int,
240          ArrayRef, { optional => 1 },
241        );
242
243       The following parameter options are supported:
244
245       "optional" Bool
246           This is an alternative way of indicating that a parameter is
247           optional.
248
249            state $check = compile(
250              Int,
251              Int, { optional => 1 },
252              Optional[Int],
253            );
254
255           The two are not exactly equivalent. The exceptions thrown will
256           differ in the type name they mention. (Int versus Optional[Int].)
257
258       "default" CodeRef|Ref|Str|Undef
259           A default may be provided for a parameter.
260
261            state $check = compile(
262              Int,
263              Int, { default => "666" },
264              Int, { default => "999" },
265            );
266
267           Supported defaults are any strings (including numerical ones),
268           "undef", and empty hashrefs and arrayrefs. Non-empty hashrefs and
269           arrayrefs are not allowed as defaults.
270
271           Alternatively, you may provide a coderef to generate a default
272           value:
273
274            state $check = compile(
275              Int,
276              Int, { default => sub { 6 * 111 } },
277              Int, { default => sub { 9 * 111 } },
278            );
279
280           That coderef may generate any value, including non-empty arrayrefs
281           and non-empty hashrefs. For undef, simple strings, numbers, and
282           empty structures, avoiding using a coderef will make your parameter
283           processing faster.
284
285           The default will be validated against the type constraint, and
286           potentially coerced.
287
288           Note that having any defaults in a specification, even if they're
289           not used in a particular check, will slightly slow down $check
290           because it means that $check can't just check @_ and return it
291           unaltered if it's valid — it needs to build a new array to return.
292
293       As a special case, the numbers 0 and 1 may be used as shortcuts for
294       Optional[Any] and Any.
295
296        # Positional parameters
297        state $check = compile(1, 0, 0);
298        my ($foo, $bar, $baz) = $check->(@_);  # $bar and $baz are optional
299
300       After any required and optional parameters may be a slurpy parameter.
301       Any additional arguments passed to $check will be slurped into an
302       arrayref or hashref and checked against the slurpy parameter.  Defaults
303       are not supported for slurpy parameters.
304
305       Example with a slurpy ArrayRef:
306
307        sub xyz {
308          state $check = compile(Int, Int, slurpy ArrayRef[Int]);
309          my ($foo, $bar, $baz) = $check->(@_);
310        }
311
312        xyz(1..5);  # $foo = 1
313                    # $bar = 2
314                    # $baz = [ 3, 4, 5 ]
315
316       Example with a slurpy HashRef:
317
318        my $check = compile(
319          Int,
320          Optional[Str],
321          slurpy HashRef[Int],
322        );
323
324        my ($x, $y, $z) = $check->(1, "y", foo => 666, bar => 999);
325        # $x is 1
326        # $y is "y"
327        # $z is { foo => 666, bar => 999 }
328
329       Any type constraints derived from ArrayRef or HashRef should work, but
330       a type does need to inherit from one of those because otherwise
331       Type::Params cannot know what kind of structure to slurp the remaining
332       arguments into.
333
334       slurpy Any is also allowed as a special case, and is treated as slurpy
335       ArrayRef.
336
337       From Type::Params 1.005000 onwards, slurpy hashrefs can be passed in as
338       a true hashref (which will be shallow cloned) rather than key-value
339       pairs.
340
341        sub xyz {
342          state $check = compile(Int, slurpy HashRef);
343          my ($num, $hr) = $check->(@_);
344          ...
345        }
346
347        xyz( 5,   foo => 1, bar => 2   );   # works
348        xyz( 5, { foo => 1, bar => 2 } );   # works from 1.005000
349
350       This feature is only implemented for slurpy hashrefs, not slurpy
351       arrayrefs.
352
353       Note that having a slurpy parameter will slightly slow down $check
354       because it means that $check can't just check @_ and return it
355       unaltered if it's valid — it needs to build a new array to return.
356
357       "validate(\@_, @spec)"
358
359       This example of "compile":
360
361        sub foo {
362          state $check = compile(@spec);
363          my @args = $check->(@_);
364          ...;
365        }
366
367       Can be written using "validate" as:
368
369        sub foo {
370          my @args = validate(\@_, @spec);
371          ...;
372        }
373
374       Performance using "compile" will always beat "validate" though.
375
376       "compile_named(@spec)"
377
378       "compile_named" is a variant of "compile" for named parameters instead
379       of positional parameters.
380
381       The format of the specification is changed to include names for each
382       parameter:
383
384        state $check = compile_named(
385          \%general_opts,
386          foo   => $type_for_foo, \%opts_for_foo,
387          bar   => $type_for_bar, \%opts_for_bar,
388          baz   => $type_for_baz, \%opts_for_baz,
389          ...,
390          extra => slurpy($slurpy_type),
391        );
392
393       The $check coderef will return a hashref.
394
395        my $check = compile_named(
396          foo => Int,
397          bar => Str, { default => "hello" },
398        );
399
400        my $args = $check->(foo => 42);
401        # $args->{foo} is 42
402        # $args->{bar} is "hello"
403
404       The %general_opts hash supports the same options as "compile" plus a
405       few additional options:
406
407       "class" ClassName
408           The check coderef will, instead of returning a simple hashref, call
409           "$class->new($hashref)" and return the result.
410
411       "constructor" Str
412           Specifies an alternative method name instead of "new" for the
413           "class" option described above.
414
415       "class" Tuple[ClassName, Str]
416           Shortcut for declaring both the "class" and "constructor" options
417           at once.
418
419       "bless" ClassName
420           Like "class", but bypass the constructor and directly bless the
421           hashref.
422
423       "named_to_list" Bool
424           Instead of returning a hashref, return a hash slice.
425
426            myfunc(bar => "x", foo => "y");
427
428            sub myfunc {
429               state $check = compile_named(
430                  { named_to_list => 1 },
431                  foo => Str, { optional => 1 },
432                  bar => Str, { optional => 1 },
433               );
434               my ($foo, $bar) = $check->(@_);
435               ...; ## $foo is "y" and $bar is "x"
436            }
437
438           The order of keys for the hash slice is the same as the order of
439           the names passed to "compile_named". For missing named parameters,
440           "undef" is returned in the list.
441
442           Basically in the above example, "myfunc" takes named parameters,
443           but receieves positional parameters.
444
445       "named_to_list" ArrayRef[Str]
446           As above, but explicitly specify the keys of the hash slice.
447
448       Like "compile", the numbers 0 and 1 may be used as shortcuts for
449       Optional[Any] and Any.
450
451        state $check = compile_named(foo => 1, bar => 0, baz => 0);
452        my $args = $check->(@_);  # $args->{bar} and $args->{baz} are optional
453
454       Slurpy parameters are slurped into a nested hashref.
455
456         my $check = compile(
457           foo    => Str,
458           bar    => Optional[Str],
459           extra  => slurpy HashRef[Str],
460         );
461         my $args = $check->(foo => "aaa", quux => "bbb");
462
463         print $args->{foo}, "\n";             # aaa
464         print $args->{extra}{quux}, "\n";     # bbb
465
466       slurpy Any is treated as slurpy HashRef.
467
468       The "head" and "tail" options are supported. This allows for a mixture
469       of positional and named arguments, as long as the positional arguments
470       are non-optional and at the head and tail of @_.
471
472         my $check = compile(
473           { head => [ Int, Int ], tail => [ CodeRef ] },
474           foo => Str,
475           bar => Str,
476           baz => Str,
477         );
478
479         my ($int1, $int2, $args, $coderef)
480           = $check->( 666, 999, foo=>'x', bar=>'y', baz=>'z', sub {...} );
481
482         say $args->{bar};  # 'y'
483
484       This can be combined with "named_to_list":
485
486         my $check = compile(
487           { head => [ Int, Int ], tail => [ CodeRef ], named_to_list => 1 },
488           foo => Str,
489           bar => Str,
490           baz => Str,
491         );
492
493         my ($int1, $int2, $foo, $bar, $baz, $coderef)
494           = $check->( 666, 999, foo=>'x', bar=>'y', baz=>'z', sub {...} );
495
496         say $bar;  # 'y'
497
498       "validate_named(\@_, @spec)"
499
500       Like "compile" has "validate", "compile_named" has "validate_named".
501       Just like "validate", it's the slower way to do things, so stick with
502       "compile_named".
503
504       "compile_named_oo(@spec)"
505
506       Here's a quick example function:
507
508          sub add_contact_to_database {
509             state $check = compile_named(
510                dbh     => Object,
511                id      => Int,
512                name    => Str,
513             );
514             my $arg = $check->(@_);
515
516             my $sth = $arg->{db}->prepare('INSERT INTO contacts VALUES (?, ?)');
517             $sth->execute($arg->{id}, $arg->{name});
518          }
519
520       Looks simple, right? Did you spot that it will always die with an error
521       message Can't call method "prepare" on an undefined value?
522
523       This is because we defined a parameter called 'dbh' but later tried to
524       refer to it as $arg{db}. Here, Perl gives us a pretty clear error, but
525       sometimes the failures will be far more subtle. Wouldn't it be nice if
526       instead we could do this?
527
528          sub add_contact_to_database {
529             state $check = compile_named_oo(
530                dbh     => Object,
531                id      => Int,
532                name    => Str,
533             );
534             my $arg = $check->(@_);
535
536             my $sth = $arg->dbh->prepare('INSERT INTO contacts VALUES (?, ?)');
537             $sth->execute($arg->id, $arg->name);
538          }
539
540       If we tried to call "$arg->db", it would fail because there was no such
541       method.
542
543       Well, that's exactly what "compile_named_oo" does.
544
545       As well as giving you nice protection against mistyped parameter names,
546       It also looks kinda pretty, I think. Hash lookups are a little faster
547       than method calls, of course (though Type::Params creates the methods
548       using Class::XSAccessor if it's installed, so they're still pretty
549       fast).
550
551       An optional parameter "foo" will also get a nifty "$arg->has_foo"
552       predicate method. Yay!
553
554       "compile_named_oo" gives you some extra options for parameters.
555
556          sub add_contact_to_database {
557             state $check = compile_named_oo(
558                dbh     => Object,
559                id      => Int,    { default => '0', getter => 'identifier' },
560                name    => Str,    { optional => 1, predicate => 'has_name' },
561             );
562             my $arg = $check->(@_);
563
564             my $sth = $arg->dbh->prepare('INSERT INTO contacts VALUES (?, ?)');
565             $sth->execute($arg->identifier, $arg->name) if $arg->has_name;
566          }
567
568       "getter" Str
569           The "getter" option lets you choose the method name for getting the
570           argument value.
571
572       "predicate" Str
573           The "predicate" option lets you choose the method name for checking
574           the existence of an argument. By setting an explicit predicate
575           method name, you can force a predicate method to be generated for
576           non-optional arguments.
577
578       The objects returned by "compile_named_oo" are blessed into lightweight
579       classes which have been generated on the fly. Don't expect the names of
580       the classes to be stable or predictable. It's probably a bad idea to be
581       checking "can", "isa", or "DOES" on any of these objects. If you're
582       doing that, you've missed the point of them.
583
584       They don't have any constructor ("new" method). The $check coderef
585       effectively is the constructor.
586
587       "validate_named_oo(\@_, @spec)"
588
589       This function doesn't even exist. :D
590
591       "multisig(@alternatives)"
592
593       Type::Params can export a "multisig" function that compiles multiple
594       alternative signatures into one, and uses the first one that works:
595
596          state $check = multisig(
597             [ Int, ArrayRef ],
598             [ HashRef, Num ],
599             [ CodeRef ],
600          );
601
602          my ($int, $arrayref) = $check->( 1, [] );      # okay
603          my ($hashref, $num)  = $check->( {}, 1.1 );    # okay
604          my ($code)           = $check->( sub { 1 } );  # okay
605
606          $check->( sub { 1 }, 1.1 );  # throws an exception
607
608       Coercions, slurpy parameters, etc still work.
609
610       The magic global "${^TYPE_PARAMS_MULTISIG}" is set to the index of the
611       first signature which succeeded.
612
613       The present implementation involves compiling each signature
614       independently, and trying them each (in their given order!) in an
615       "eval" block. The only slightly intelligent part is that it checks if
616       "scalar(@_)" fits into the signature properly (taking into account
617       optional and slurpy parameters), and skips evals which couldn't
618       possibly succeed.
619
620       It's also possible to list coderefs as alternatives in "multisig":
621
622          state $check = multisig(
623             [ Int, ArrayRef ],
624             sub { ... },
625             [ HashRef, Num ],
626             [ CodeRef ],
627             compile_named( needle => Value, haystack => Ref ),
628          );
629
630       The coderef is expected to die if that alternative should be abandoned
631       (and the next alternative tried), or return the list of accepted
632       parameters. Here's a full example:
633
634          sub get_from {
635             state $check = multisig(
636                [ Int, ArrayRef ],
637                [ Str, HashRef ],
638                sub {
639                   my ($meth, $obj);
640                   die unless is_Object($obj);
641                   die unless $obj->can($meth);
642                   return ($meth, $obj);
643                },
644             );
645
646             my ($needle, $haystack) = $check->(@_);
647
648             for (${^TYPE_PARAMS_MULTISIG}) {
649                return $haystack->[$needle] if $_ == 0;
650                return $haystack->{$needle} if $_ == 1;
651                return $haystack->$needle   if $_ == 2;
652             }
653          }
654
655          get_from(0, \@array);      # returns $array[0]
656          get_from('foo', \%hash);   # returns $hash{foo}
657          get_from('foo', $obj);     # returns $obj->foo
658
659       The default error message is just "Parameter validation failed".  You
660       can pass an option hashref as the first argument with an informative
661       message string:
662
663          sub foo {
664             state $OptionsDict = Dict[...];
665             state $check = multisig(
666                { message => 'USAGE: $object->foo(\%options?, $string)' },
667                [ Object, $OptionsDict, StringLike ],
668                [ Object, StringLike ],
669             );
670             my ($self, @args) = $check->(@_);
671             my ($opts, $str)  = ${^TYPE_PARAMS_MULTISIG} ? ({}, @args) : @_;
672             ...;
673          }
674
675          $obj->foo(\%opts, "Hello");
676          $obj->foo("World");
677
678       "wrap_subs( $subname1, $wrapper1, ... )"
679
680       It's possible to turn the check inside-out and instead of the sub
681       calling the check, the check can call the original sub.
682
683       Normal way:
684
685          use Type::Param qw(compile);
686          use Types::Standard qw(Int Str);
687
688          sub foobar {
689             state $check = compile(Int, Str);
690             my ($foo, $bar) = @_;
691             ...;
692          }
693
694       Inside-out way:
695
696          use Type::Param qw(wrap_subs);
697          use Types::Standard qw(Int Str);
698
699          sub foobar {
700             my ($foo, $bar) = @_;
701             ...;
702          }
703
704          wrap_subs foobar => [Int, Str];
705
706       "wrap_subs" takes a hash of subs to wrap. The keys are the sub names
707       and the values are either arrayrefs of arguments to pass to "compile"
708       to make a check, or coderefs that have already been built by "compile",
709       "compile_named", or "compile_named_oo".
710
711       "wrap_methods( $subname1, $wrapper1, ... )"
712
713       "wrap_methods" also exists, which shifts off the invocant from @_
714       before the check, but unshifts it before calling the original sub.
715
716          use Type::Param qw(wrap_subs);
717          use Types::Standard qw(Int Str);
718
719          sub foobar {
720             my ($self, $foo, $bar) = @_;
721             ...;
722          }
723
724          wrap_subs foobar => [Int, Str];
725
726       Invocant
727
728       Type::Params exports a type Invocant on request. This gives you a type
729       constraint which accepts classnames and blessed objects.
730
731        use Type::Params qw( compile Invocant );
732
733        sub my_method {
734          state $check = compile(Invocant, ArrayRef, Int);
735          my ($self_or_class, $arr, $ix) = $check->(@_);
736
737          return $arr->[ $ix ];
738        }
739

ENVIRONMENT

741       "PERL_TYPE_PARAMS_XS"
742           Affects the building of accessors for "compile_named_oo". If set to
743           true, will use Class::XSAccessor. If set to false, will use pure
744           Perl. If this environment variable does not exist, will use
745           Class::XSAccessor if it is available.
746

BUGS

748       Please report any bugs to
749       <http://rt.cpan.org/Dist/Display.html?Queue=Type-Tiny>.
750

SEE ALSO

752       The Type::Tiny homepage <https://typetiny.toby.ink/>.
753
754       Type::Tiny, Type::Coercion, Types::Standard.
755

AUTHOR

757       Toby Inkster <tobyink@cpan.org>.
758
760       This software is copyright (c) 2013-2014, 2017-2020 by Toby Inkster.
761
762       This is free software; you can redistribute it and/or modify it under
763       the same terms as the Perl 5 programming language system itself.
764

DISCLAIMER OF WARRANTIES

766       THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
767       WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
768       MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
769
770
771
772perl v5.32.0                      2020-09-17                   Type::Params(3)
Impressum