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       "want_source" Bool
132           Instead of returning a coderef, return Perl source code string.
133           Handy for debugging.
134
135       "want_details" Bool
136           Instead of returning a coderef, return a hashref of stuff including
137           the coderef. This is mostly for people extending Type::Params and I
138           won't go into too many details about what else this hashref
139           contains.
140
141       "description" Str
142           Description of the coderef that will show up in stack traces.
143           Defaults to "parameter validation for X" where X is the caller sub
144           name.
145
146       "subname" Str
147           If you wish to use the default description, but need to change the
148           sub name, use this.
149
150       "caller_level" Int
151           If you wish to use the default description, but need to change the
152           caller level for detecting the sub name, use this.
153
154       The types for each parameter may be any Type::Tiny type constraint, or
155       anything that Type::Tiny knows how to coerce into a Type::Tiny type
156       constraint, such as a MooseX::Types type constraint or a coderef.
157
158       Type coercions are automatically applied for all types that have
159       coercions.
160
161       If you wish to avoid coercions for a type, use Type::Tiny's
162       "no_coercions" method.
163
164        my $check = compile(
165          Int,
166          ArrayRef->of(Bool)->no_coercions,
167        );
168
169       Note that having any coercions in a specification, even if they're not
170       used in a particular check, will slightly slow down $check because it
171       means that $check can't just check @_ and return it unaltered if it's
172       valid — it needs to build a new array to return.
173
174       Optional parameters can be given using the Optional[] type constraint.
175       In the example above, the third parameter is optional.  If it's
176       present, it's required to be an arrayref, but if it's absent, it is
177       ignored.
178
179       Optional parameters need to be after required parameters in the spec.
180
181       An alternative way to specify optional parameters is using a parameter
182       options hashref.
183
184        my $check = compile(
185          Str,
186          Int,
187          ArrayRef, { optional => 1 },
188        );
189
190       The following parameter options are supported:
191
192       "optional" Bool
193           This is an alternative way of indicating that a parameter is
194           optional.
195
196            state $check = compile(
197              Int,
198              Int, { optional => 1 },
199              Optional[Int],
200            );
201
202           The two are not exactly equivalent. The exceptions thrown will
203           differ in the type name they mention. (Int versus Optional[Int].)
204
205       "default" CodeRef|Ref|Str|Undef
206           A default may be provided for a parameter.
207
208            state $check = compile(
209              Int,
210              Int, { default => "666" },
211              Int, { default => "999" },
212            );
213
214           Supported defaults are any strings (including numerical ones),
215           "undef", and empty hashrefs and arrayrefs. Non-empty hashrefs and
216           arrayrefs are not allowed as defaults.
217
218           Alternatively, you may provide a coderef to generate a default
219           value:
220
221            state $check = named(
222              Int,
223              Int, { default => sub { 6 * 111 } },
224              Int, { default => sub { 9 * 111 } },
225            );
226
227           That coderef may generate any value, including non-empty arrayrefs
228           and non-empty hashrefs. For undef, simple strings, numbers, and
229           empty structures, avoiding using a coderef will make your parameter
230           processing faster.
231
232           The default will be validated against the type constraint, and
233           potentially coerced.
234
235           Note that having any defaults in a specification, even if they're
236           not used in a particular check, will slightly slow down $check
237           because it means that $check can't just check @_ and return it
238           unaltered if it's valid — it needs to build a new array to return.
239
240       As a special case, the numbers 0 and 1 may be used as shortcuts for
241       Optional[Any] and Any.
242
243        # Positional parameters
244        state $check = compile(1, 0, 0);
245        my ($foo, $bar, $baz) = $check->(@_);  # $bar and $baz are optional
246
247       After any required and optional parameters may be a slurpy parameter.
248       Any additional arguments passed to $check will be slurped into an
249       arrayref or hashref and checked against the slurpy parameter.  Defaults
250       are not supported for slurpy parameters.
251
252       Example with a slurpy ArrayRef:
253
254        sub xyz {
255          state $check = compile(Int, Int, slurpy ArrayRef[Int]);
256          my ($foo, $bar, $baz) = $check->(@_);
257        }
258
259        xyz(1..5);  # $foo = 1
260                    # $bar = 2
261                    # $baz = [ 3, 4, 5 ]
262
263       Example with a slurpy HashRef:
264
265        my $check = compile(
266          Int,
267          Optional[Str],
268          slurpy HashRef[Int],
269        );
270
271        my ($x, $y, $z) = $check->(1, "y", foo => 666, bar => 999);
272        # $x is 1
273        # $y is "y"
274        # $z is { foo => 666, bar => 999 }
275
276       Any type constraints derived from ArrayRef or HashRef should work, but
277       a type does need to inherit from one of those because otherwise
278       Type::Params cannot know what kind of structure to slurp the remaining
279       arguments into.
280
281       slurpy Any is also allowed as a special case, and is treated as slurpy
282       ArrayRef.
283
284       From Type::Params 1.005000 onwards, slurpy hashrefs can be passed in as
285       a true hashref (which will be shallow cloned) rather than key-value
286       pairs.
287
288        sub xyz {
289          state $check = compile(Int, slurpy HashRef);
290          my ($num, $hr) = $check->(@_);
291          ...
292        }
293
294        xyz( 5,   foo => 1, bar => 2   );   # works
295        xyz( 5, { foo => 1, bar => 2 } );   # works from 1.005000
296
297       This feature is only implemented for slurpy hashrefs, not slurpy
298       arrayrefs.
299
300       Note that having a slurpy parameter will slightly slow down $check
301       because it means that $check can't just check @_ and return it
302       unaltered if it's valid — it needs to build a new array to return.
303
304       "validate(\@_, @spec)"
305
306       This example of "compile":
307
308        sub foo {
309          state $check = compile(@spec);
310          my @args = $check->(@_);
311          ...;
312        }
313
314       Can be written using "validate" as:
315
316        sub foo {
317          my @args = validate(\@_, @spec);
318          ...;
319        }
320
321       Performance using "compile" will always beat "validate" though.
322
323       "compile_named(@spec)"
324
325       "compile_named" is a variant of "compile" for named parameters instead
326       of positional parameters.
327
328       The format of the specification is changed to include names for each
329       parameter:
330
331        state $check = compile_named(
332          \%general_opts,
333          foo => $type_for_foo, \%opts_for_foo,
334          bar => $type_for_bar, \%opts_for_bar,
335          baz => $type_for_baz, \%opts_for_baz,
336          ...,
337          slurpy($slurpy_type),
338        );
339
340       The $check coderef will return a hashref.
341
342        my $check = compile_named(
343          foo => Int,
344          bar => Str, { default => "hello" },
345        );
346
347        my $args = $check->(foo => 42);
348        # $args->{foo} is 42
349        # $args->{bar} is "hello"
350
351       The %general_opts hash supports the same options as "compile" plus a
352       few additional options:
353
354       "class" ClassName
355           The check coderef will, instead of returning a simple hashref, call
356           "$class->new($hashref)" and return the result.
357
358       "constructor" Str
359           Specifies an alternative method name instead of "new" for the
360           "class" option described above.
361
362       "class" Tuple[ClassName, Str]
363           Shortcut for declaring both the "class" and "constructor" options
364           at once.
365
366       "bless" ClassName
367           Like "class", but bypass the constructor and directly bless the
368           hashref.
369
370       "named_to_list" Bool
371           Instead of returning a hashref, return a hash slice.
372
373            myfunc(bar => "x", foo => "y");
374
375            sub myfunc {
376               state $check = compile_named(
377                  { named_to_list => 1 },
378                  foo => Str, { optional => 1 },
379                  bar => Str, { optional => 1 },
380               );
381               my ($foo, $bar) = $check->(@_);
382               ...; ## $foo is "y" and $bar is "x"
383            }
384
385           The order of keys for the hash slice is the same as the order of
386           the names passed to "compile_named". For missing named parameters,
387           "undef" is returned in the list.
388
389           Basically in the above example, "myfunc" takes named parameters,
390           but receieves positional parameters.
391
392       "named_to_list" ArrayRef[Str]
393           As above, but explicitly specify the keys of the hash slice.
394
395       Like "compile", the numbers 0 and 1 may be used as shortcuts for
396       Optional[Any] and Any.
397
398        state $check = compile_named(foo => 1, bar => 0, baz => 0);
399        my $args = $check->(@_);  # $args->{bar} and $args->{baz} are optional
400
401       Slurpy parameters are supported as you'd expect.
402
403       slurpy Any is treated as slurpy HashRef.
404
405       "validate_named(\@_, @spec)"
406
407       Like "compile" has "validate", "compile_named" has "validate_named".
408       Just like "validate", it's the slower way to do things, so stick with
409       "compile_named".
410
411       "compile_named_oo(@spec)"
412
413       Here's a quick example function:
414
415          sub add_contact_to_database {
416             state $check = compile_named(
417                dbh     => Object,
418                id      => Int,
419                name    => Str,
420             );
421             my $arg = $check->(@_);
422
423             my $sth = $arg->{db}->prepare('INSERT INTO contacts VALUES (?, ?)');
424             $sth->execute($arg->{id}, $arg->{name});
425          }
426
427       Looks simple, right? Did you spot that it will always die with an error
428       message Can't call method "prepare" on an undefined value?
429
430       This is because we defined a parameter called 'dbh' but later tried to
431       refer to it as $arg{db}. Here, Perl gives us a pretty clear error, but
432       sometimes the failures will be far more subtle. Wouldn't it be nice if
433       instead we could do this?
434
435          sub add_contact_to_database {
436             state $check = compile_named_oo(
437                dbh     => Object,
438                id      => Int,
439                name    => Str,
440             );
441             my $arg = $check->(@_);
442
443             my $sth = $arg->dbh->prepare('INSERT INTO contacts VALUES (?, ?)');
444             $sth->execute($arg->id, $arg->name);
445          }
446
447       If we tried to call "$arg->db", it would fail because there was no such
448       method.
449
450       Well, that's exactly what "compile_named_oo" does.
451
452       As well as giving you nice protection against mistyped parameter names,
453       It also looks kinda pretty, I think. Hash lookups are a little faster
454       than method calls, of course (though Type::Params creates the methods
455       using Class::XSAccessor if it's installed, so they're still pretty
456       fast).
457
458       An optional parameter "foo" will also get a nifty "$arg->has_foo"
459       predicate method. Yay!
460
461       "compile_named_oo" gives you some extra options for parameters.
462
463          sub add_contact_to_database {
464             state $check = compile_named_oo(
465                dbh     => Object,
466                id      => Int,    { default => '0', getter => 'identifier' },
467                name    => Str,    { optional => 1, predicate => 'has_name' },
468             );
469             my $arg = $check->(@_);
470
471             my $sth = $arg->dbh->prepare('INSERT INTO contacts VALUES (?, ?)');
472             $sth->execute($arg->identifier, $arg->name) if $arg->has_name;
473          }
474
475       "getter" Str
476           The "getter" option lets you choose the method name for getting the
477           argument value.
478
479       "predicate" Str
480           The "predicate" option lets you choose the method name for checking
481           the existence of an argument. By setting an explicit predicate
482           method name, you can force a predicate method to be generated for
483           non-optional arguments.
484
485       The objects returned by "compile_named_oo" are blessed into lightweight
486       classes which have been generated on the fly. Don't expect the names of
487       the classes to be stable or predictable. It's probably a bad idea to be
488       checking "can", "isa", or "DOES" on any of these objects. If you're
489       doing that, you've missed the point of them.
490
491       They don't have any constructor ("new" method). The $check coderef
492       effectively is the constructor.
493
494       "validate_named_oo(\@_, @spec)"
495
496       This function doesn't even exist. :D
497
498       "multisig(@alternatives)"
499
500       Type::Params can export a "multisig" function that compiles multiple
501       alternative signatures into one, and uses the first one that works:
502
503          state $check = multisig(
504             [ Int, ArrayRef ],
505             [ HashRef, Num ],
506             [ CodeRef ],
507          );
508
509          my ($int, $arrayref) = $check->( 1, [] );      # okay
510          my ($hashref, $num)  = $check->( {}, 1.1 );    # okay
511          my ($code)           = $check->( sub { 1 } );  # okay
512
513          $check->( sub { 1 }, 1.1 );  # throws an exception
514
515       Coercions, slurpy parameters, etc still work.
516
517       The magic global "${^TYPE_PARAMS_MULTISIG}" is set to the index of the
518       first signature which succeeded.
519
520       The present implementation involves compiling each signature
521       independently, and trying them each (in their given order!) in an
522       "eval" block. The only slightly intelligent part is that it checks if
523       "scalar(@_)" fits into the signature properly (taking into account
524       optional and slurpy parameters), and skips evals which couldn't
525       possibly succeed.
526
527       It's also possible to list coderefs as alternatives in "multisig":
528
529          state $check = multisig(
530             [ Int, ArrayRef ],
531             sub { ... },
532             [ HashRef, Num ],
533             [ CodeRef ],
534             compile_named( needle => Value, haystack => Ref ),
535          );
536
537       The coderef is expected to die if that alternative should be abandoned
538       (and the next alternative tried), or return the list of accepted
539       parameters. Here's a full example:
540
541          sub get_from {
542             state $check = multisig(
543                [ Int, ArrayRef ],
544                [ Str, HashRef ],
545                sub {
546                   my ($meth, $obj);
547                   die unless is_Object($obj);
548                   die unless $obj->can($meth);
549                   return ($meth, $obj);
550                },
551             );
552
553             my ($needle, $haystack) = $check->(@_);
554
555             for (${^TYPE_PARAMS_MULTISIG}) {
556                return $haystack->[$needle] if $_ == 0;
557                return $haystack->{$needle} if $_ == 1;
558                return $haystack->$needle   if $_ == 2;
559             }
560          }
561
562          get_from(0, \@array);      # returns $array[0]
563          get_from('foo', \%hash);   # returns $hash{foo}
564          get_from('foo', $obj);     # returns $obj->foo
565
566       The default error message is just "Parameter validation failed".  You
567       can pass an option hashref as the first argument with an informative
568       message string:
569
570          sub foo {
571             state $OptionsDict = Dict[...];
572             state $check = multisig(
573                { message => 'USAGE: $object->foo(\%options?, $string)' },
574                [ Object, $OptionsDict, StringLike ],
575                [ Object, StringLike ],
576             );
577             my ($self, @args) = $check->(@_);
578             my ($opts, $str)  = ${^TYPE_PARAMS_MULTISIG} ? ({}, @args) : @_;
579             ...;
580          }
581
582          $obj->foo(\%opts, "Hello");
583          $obj->foo("World");
584
585       "wrap_subs( $subname1, $wrapper1, ... )"
586
587       It's possible to turn the check inside-out and instead of the sub
588       calling the check, the check can call the original sub.
589
590       Normal way:
591
592          use Type::Param qw(compile);
593          use Types::Standard qw(Int Str);
594
595          sub foobar {
596             state $check = compile(Int, Str);
597             my ($foo, $bar) = @_;
598             ...;
599          }
600
601       Inside-out way:
602
603          use Type::Param qw(wrap_subs);
604          use Types::Standard qw(Int Str);
605
606          sub foobar {
607             my ($foo, $bar) = @_;
608             ...;
609          }
610
611          wrap_subs foobar => [Int, Str];
612
613       "wrap_subs" takes a hash of subs to wrap. The keys are the sub names
614       and the values are either arrayrefs of arguments to pass to "compile"
615       to make a check, or coderefs that have already been built by "compile",
616       "compile_named", or "compile_named_oo".
617
618       "wrap_methods( $subname1, $wrapper1, ... )"
619
620       "wrap_methods" also exists, which shifts off the invocant from @_
621       before the check, but unshifts it before calling the original sub.
622
623          use Type::Param qw(wrap_subs);
624          use Types::Standard qw(Int Str);
625
626          sub foobar {
627             my ($self, $foo, $bar) = @_;
628             ...;
629          }
630
631          wrap_subs foobar => [Int, Str];
632
633       Invocant
634
635       Type::Params exports a type Invocant on request. This gives you a type
636       constraint which accepts classnames and blessed objects.
637
638        use Type::Params qw( compile Invocant );
639
640        sub my_method {
641          state $check = compile(Invocant, ArrayRef, Int);
642          my ($self_or_class, $arr, $ix) = $check->(@_);
643
644          return $arr->[ $ix ];
645        }
646

ENVIRONMENT

648       "PERL_TYPE_PARAMS_XS"
649           Affects the building of accessors for "compile_named_oo". If set to
650           true, will use Class::XSAccessor. If set to false, will use pure
651           Perl. If this environment variable does not exist, will use
652           Class::XSAccessor if it is available.
653

BUGS

655       Please report any bugs to
656       <http://rt.cpan.org/Dist/Display.html?Queue=Type-Tiny>.
657

SEE ALSO

659       The Type::Tiny homepage <http://typetiny.toby.ink/>.
660
661       Type::Tiny, Type::Coercion, Types::Standard.
662

AUTHOR

664       Toby Inkster <tobyink@cpan.org>.
665
667       This software is copyright (c) 2013-2014, 2017-2020 by Toby Inkster.
668
669       This is free software; you can redistribute it and/or modify it under
670       the same terms as the Perl 5 programming language system itself.
671

DISCLAIMER OF WARRANTIES

673       THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
674       WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
675       MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
676
677
678
679perl v5.30.1                      2020-02-12                   Type::Params(3)
Impressum