1Type::Params(3) User Contributed Perl Documentation Type::Params(3)
2
3
4
6 Type::Params - Params::Validate-like parameter validation using
7 Type::Tiny type constraints and coercions
8
10 use v5.10;
11 use strict;
12 use warnings;
13
14 use Type::Params qw( compile );
15 use Types::Standard qw( slurpy Str ArrayRef Num );
16
17 sub deposit_monies
18 {
19 state $check = compile( Str, Str, slurpy ArrayRef[Num] );
20 my ($sort_code, $account_number, $monies) = $check->(@_);
21
22 my $account = Local::BankAccount->new($sort_code, $account_number);
23 $account->deposit($_) for @$monies;
24 }
25
26 deposit_monies("12-34-56", "11223344", 1.2, 3, 99.99);
27
29 This module is covered by the Type-Tiny stability policy.
30
32 Type::Params uses Type::Tiny constraints to validate the parameters to
33 a sub. It takes the slightly unorthodox approach of separating
34 validation into two stages:
35
36 1. Compiling the parameter specification into a coderef; then
37
38 2. Using the coderef to validate parameters.
39
40 The first stage is slow (it might take a couple of milliseconds), but
41 you only need to do it the first time the sub is called. The second
42 stage is fast; according to my benchmarks faster even than the XS
43 version of Params::Validate.
44
45 If you're using a modern version of Perl, you can use the "state"
46 keyword which was a feature added to Perl in 5.10. If you're stuck on
47 Perl 5.8, the example from the SYNOPSIS could be rewritten as:
48
49 my $deposit_monies_check;
50 sub deposit_monies
51 {
52 $deposit_monies_check ||= compile( Str, Str, slurpy ArrayRef[Num] );
53 my ($sort_code, $account_number, $monies) = $deposit_monies_check->(@_);
54
55 ...;
56 }
57
58 Not quite as neat, but not awful either.
59
60 There's a shortcut reducing it to one step:
61
62 use Type::Params qw( validate );
63
64 sub deposit_monies
65 {
66 my ($sort_code, $account_number, $monies) =
67 validate( \@_, Str, Str, slurpy ArrayRef[Num] );
68
69 ...;
70 }
71
72 Type::Params has a few tricks up its sleeve to make sure performance
73 doesn't suffer too much with the shortcut, but it's never going to be
74 as fast as the two stage compile/execute.
75
77 This module offers one-stage ("validate") and two-stage ("compile" then
78 "check") variants of parameter checking for you to use. Performance
79 with the two-stage variant will always beat the one stage variant — I
80 cannot think of many reasons you'd want to use the one-stage version.
81
82 # One-stage, positional parameters
83 my @args = validate(\@_, @spec);
84
85 # Two-stage, positional parameters
86 state $check = compile(@spec);
87 my @args = $check->(@_);
88
89 # One-stage, named parameters
90 my $args = validate_named(\@_, @spec);
91
92 # Two-stage, named parameters
93 state $check = compile_named(@spec);
94 my $args = $check->(@_);
95
96 Use "compile" and "compile_named", not "validate" and "validate_named".
97
99 The @spec is where most of the magic happens.
100
101 The generalized form of specifications for positional parameters is:
102
103 @spec = (
104 \%general_opts,
105 $type_for_arg_1, \%opts_for_arg_1,
106 $type_for_arg_2, \%opts_for_arg_2,
107 $type_for_arg_3, \%opts_for_arg_3,
108 ...,
109 slurpy($slurpy_type),
110 );
111
112 And for named parameters:
113
114 @spec = (
115 \%general_opts,
116 foo => $type_for_foo, \%opts_for_foo,
117 bar => $type_for_bar, \%opts_for_bar,
118 baz => $type_for_baz, \%opts_for_baz,
119 ...,
120 slurpy($slurpy_type),
121 );
122
123 Option hashrefs can simply be omitted if you don't need to specify any
124 particular options.
125
126 The "slurpy" function is exported by Types::Standard. It may be omitted
127 if not needed.
128
129 General Options
130 Currently supported general options are:
131
132 "want_source => Bool"
133 Instead of returning a coderef, return Perl source code string.
134 Handy for debugging.
135
136 "want_details => Bool"
137 Instead of returning a coderef, return a hashref of stuff including
138 the coderef. This is mostly for people extending Type::Params and I
139 won't go into too many details about what else this hashref
140 contains.
141
142 "class => ClassName"
143 Named parameters only. The check coderef will, instead of returning
144 a simple hashref, call "$class->new($hashref)" and return a proper
145 object.
146
147 "constructor => Str"
148 Named parameters only. Specify an alternative method name instead
149 of "new" for the "class" option described above.
150
151 "class => Tuple[ClassName, Str]"
152 Named parameters only. Given a class name and constructor name
153 pair, the check coderef will, instead of returning a simple
154 hashref, call "$class->$constructor($hashref)" and return a proper
155 object. Shortcut for declaring both the "class" and "constructor"
156 options at once.
157
158 "bless => ClassName"
159 Named parameters only. Bypass the constructor entirely and directly
160 bless the hashref.
161
162 "description => Str"
163 Description of the coderef that will show up in stack traces.
164 Defaults to "parameter validation for X" where X is the caller sub
165 name.
166
167 "subname => Str"
168 If you wish to use the default description, but need to change the
169 sub name, use this.
170
171 "caller_level => Int"
172 If you wish to use the default description, but need to change the
173 caller level for detecting the sub name, use this.
174
175 Type Constraints
176 The types for each parameter may be any Type::Tiny type constraint, or
177 anything that Type::Tiny knows how to coerce into a Type::Tiny type
178 constraint, such as a MooseX::Types type constraint or a coderef.
179
180 Optional Parameters
181 The "Optional" parameterizable type constraint from Types::Standard may
182 be used to indicate optional parameters.
183
184 # Positional parameters
185 state $check = compile(Int, Optional[Int], Optional[Int]);
186 my ($foo, $bar, $baz) = $check->(@_); # $bar and $baz are optional
187
188 # Named parameters
189 state $check = compile(
190 foo => Int,
191 bar => Optional[Int],
192 baz => Optional[Int],
193 );
194 my $args = $check->(@_); # $args->{bar} and $args->{baz} are optional
195
196 As a special case, the numbers 0 and 1 may be used as shortcuts for
197 "Optional[Any]" and "Any".
198
199 # Positional parameters
200 state $check = compile(1, 0, 0);
201 my ($foo, $bar, $baz) = $check->(@_); # $bar and $baz are optional
202
203 # Named parameters
204 state $check = compile_named(foo => 1, bar => 0, baz => 0);
205 my $args = $check->(@_); # $args->{bar} and $args->{baz} are optional
206
207 If you're using positional parameters, then required parameters must
208 precede any optional ones.
209
210 Slurpy Parameters
211 Specifications may include a single slurpy parameter which should have
212 a type constraint derived from "ArrayRef" or "HashRef". ("Any" is also
213 allowed, which is interpreted as "ArrayRef" in the case of positional
214 parameters, and "HashRef" in the case of named parameters.)
215
216 If a slurpy parameter is provided in the specification, the $check
217 coderef will slurp up any remaining arguments from @_ (after required
218 and optional parameters have been removed), validate it against the
219 given slurpy type, and return it as a single arrayref/hashref.
220
221 For example:
222
223 sub xyz {
224 state $check = compile(Int, Int, slurpy ArrayRef[Int]);
225 my ($foo, $bar, $baz) = $check->(@_);
226 }
227
228 xyz(1..5); # $foo = 1
229 # $bar = 2
230 # $baz = [ 3, 4, 5 ]
231
232 A specification have one or zero slurpy parameters. If there is a
233 slurpy parameter, it must be the final one.
234
235 Note that having a slurpy parameter will slightly slow down $check
236 because it means that $check can't just check @_ and return it
237 unaltered if it's valid — it needs to build a new array to return.
238
239 Type Coercion
240 Type coercions are automatically applied for all types that have
241 coercions.
242
243 my $RoundedInt = Int->plus_coercions(Num, q{ int($_) });
244
245 state $check = compile($RoundedInt, $RoundedInt);
246 my ($foo, $bar) = $check->(@_);
247
248 # if @_ is (1.1, 2.2), then $foo is 1 and $bar is 2.
249
250 Coercions carry over into structured types such as "ArrayRef"
251 automatically:
252
253 sub delete_articles
254 {
255 state $check = compile( Object, slurpy ArrayRef[$RoundedInt] );
256 my ($db, $articles) = $check->(@_);
257
258 $db->select_article($_)->delete for @$articles;
259 }
260
261 # delete articles 1, 2 and 3
262 delete_articles($my_db, 1.1, 2.2, 3.3);
263
264 That's a Types::Standard feature rather than something specific to
265 Type::Params.
266
267 Note that having any coercions in a specification, even if they're not
268 used in a particular check, will slightly slow down $check because it
269 means that $check can't just check @_ and return it unaltered if it's
270 valid — it needs to build a new array to return.
271
272 Parameter Options
273 The type constraint for a parameter may be followed by a hashref of
274 options for it.
275
276 The following options are supported:
277
278 "optional => Bool"
279 This is an alternative way of indicating that a parameter is
280 optional.
281
282 state $check = compile_named(
283 foo => Int,
284 bar => Int, { optional => 1 },
285 baz => Optional[Int],
286 );
287
288 The two are not exactly equivalent. If you were to set "bar" to a
289 non-integer, it would throw an exception about the "Int" type
290 constraint being violated. If "baz" were a non-integer, the
291 exception would mention the "Optional[Int]" type constraint
292 instead.
293
294 "default => CodeRef|Ref|Str|Undef"
295 A default may be provided for a parameter.
296
297 state $check = compile_named(
298 foo => Int,
299 bar => Int, { default => "666" },
300 baz => Int, { default => "999" },
301 );
302
303 Supported defaults are any strings (including numerical ones),
304 "undef", and empty hashrefs and arrayrefs. Non-empty hashrefs and
305 arrayrefs are not allowed as defaults.
306
307 Alternatively, you may provide a coderef to generate a default
308 value:
309
310 state $check = compile_named(
311 foo => Int,
312 bar => Int, { default => sub { 6 * 111 } },
313 baz => Int, { default => sub { 9 * 111 } },
314 );
315
316 That coderef may generate any value, including non-empty arrayrefs
317 and non-empty hashrefs. For undef, simple strings, numbers, and
318 empty structures, avoiding using a coderef will make your parameter
319 processing faster.
320
321 The default will be validated against the type constraint, and
322 potentially coerced.
323
324 Defaults are not supported for slurpy parameters.
325
326 Note that having any defaults in a specification, even if they're
327 not used in a particular check, will slightly slow down $check
328 because it means that $check can't just check @_ and return it
329 unaltered if it's valid — it needs to build a new array to return.
330
332 Type::Params can export a "multisig" function that compiles multiple
333 alternative signatures into one, and uses the first one that works:
334
335 state $check = multisig(
336 [ Int, ArrayRef ],
337 [ HashRef, Num ],
338 [ CodeRef ],
339 );
340
341 my ($int, $arrayref) = $check->( 1, [] ); # okay
342 my ($hashref, $num) = $check->( {}, 1.1 ); # okay
343 my ($code) = $check->( sub { 1 } ); # okay
344
345 $check->( sub { 1 }, 1.1 ); # throws an exception
346
347 Coercions, slurpy parameters, etc still work.
348
349 The magic global "${^TYPE_PARAMS_MULTISIG}" is set to the index of the
350 first signature which succeeded.
351
352 The present implementation involves compiling each signature
353 independently, and trying them each (in their given order!) in an
354 "eval" block. The only slightly intelligent part is that it checks if
355 "scalar(@_)" fits into the signature properly (taking into account
356 optional and slurpy parameters), and skips evals which couldn't
357 possibly succeed.
358
359 It's also possible to list coderefs as alternatives in "multisig":
360
361 state $check = multisig(
362 [ Int, ArrayRef ],
363 sub { ... },
364 [ HashRef, Num ],
365 [ CodeRef ],
366 compile_named( needle => Value, haystack => Ref ),
367 );
368
369 The coderef is expected to die if that alternative should be abandoned
370 (and the next alternative tried), or return the list of accepted
371 parameters. Here's a full example:
372
373 sub get_from {
374 state $check = multisig(
375 [ Int, ArrayRef ],
376 [ Str, HashRef ],
377 sub {
378 my ($meth, $obj);
379 die unless is_Object($obj);
380 die unless $obj->can($meth);
381 return ($meth, $obj);
382 },
383 );
384
385 my ($needle, $haystack) = $check->(@_);
386
387 for (${^TYPE_PARAMS_MULTISIG) {
388 return $haystack->[$needle] if $_ == 0;
389 return $haystack->{$needle} if $_ == 1;
390 return $haystack->$needle if $_ == 2;
391 }
392 }
393
394 get_from(0, \@array); # returns $array[0]
395 get_from('foo', \%hash); # returns $hash{foo}
396 get_from('foo', $obj); # returns $obj->foo
397
399 Here's a quick example function:
400
401 sub add_contact_to_database {
402 state $check = compile_named(
403 dbh => Object,
404 id => Int,
405 name => Str,
406 );
407 my $arg = $check->(@_);
408
409 my $sth = $arg->{db}->prepare('INSERT INTO contacts VALUES (?, ?)');
410 $sth->execute($arg->{id}, $arg->{name});
411 }
412
413 Looks simple, right? Did you spot that it will always die with an error
414 message Can't call method "prepare" on an undefined value?
415
416 This is because we defined a parameter called 'dbh' but later tried to
417 refer to it as $arg{db}. Here, Perl gives us a pretty clear error, but
418 sometimes the failures will be far more subtle. Wouldn't it be nice if
419 instead we could do this?
420
421 sub add_contact_to_database {
422 state $check = compile_named_oo(
423 dbh => Object,
424 id => Int,
425 name => Str,
426 );
427 my $arg = $check->(@_);
428
429 my $sth = $arg->dbh->prepare('INSERT INTO contacts VALUES (?, ?)');
430 $sth->execute($arg->id, $arg->name);
431 }
432
433 If we tried to call "$arg->db", it would fail because there was no such
434 method.
435
436 Well, that's exactly what "compile_named_oo" does.
437
438 As well as giving you nice protection against mistyped parameter names,
439 It also looks kinda pretty, I think. Hash lookups are a little faster
440 than method calls, of course (though Type::Params creates the methods
441 using Class::XSAccessor if it's installed, so they're still pretty
442 fast).
443
444 An optional parameter "foo" will also get a nifty "$arg->has_foo"
445 predicate method. Yay!
446
447 Options
448 "compile_named_oo" gives you some extra options for parameters.
449
450 sub add_contact_to_database {
451 state $check = compile_named_oo(
452 dbh => Object,
453 id => Int, { default => '0', getter => 'identifier' },
454 name => Str, { optional => 1, predicate => 'has_name' },
455 );
456 my $arg = $check->(@_);
457
458 my $sth = $arg->dbh->prepare('INSERT INTO contacts VALUES (?, ?)');
459 $sth->execute($arg->identifier, $arg->name) if $arg->has_name;
460 }
461
462 The "getter" option lets you choose the method name for getting the
463 argument value. The "predicate" option lets you choose the method name
464 for checking the existence of an argument.
465
466 By setting an explicit predicate method name, you can force a predicate
467 method to be generated for non-optional arguments.
468
469 Classes
470 The objects returned by "compile_named_oo" are blessed into lightweight
471 classes which have been generated on the fly. Don't expect the names of
472 the classes to be stable or predictable. It's probably a bad idea to be
473 checking "can", "isa", or "DOES" on any of these objects. If you're
474 doing that, you've missed the point of them.
475
476 They don't have any constructor ("new" method). The $check coderef
477 effectively is the constructor.
478
480 Mixed Positional and Named Parameters
481 This can be faked using positional parameters and a slurpy dictionary.
482
483 state $check = compile(
484 Int,
485 slurpy Dict[
486 foo => Int,
487 bar => Optional[Int],
488 baz => Optional[Int],
489 ],
490 );
491
492 @_ = (42, foo => 21); # ok
493 @_ = (42, foo => 21, bar => 84); # ok
494 @_ = (42, foo => 21, bar => 10.5); # not ok
495 @_ = (42, foo => 21, quux => 84); # not ok
496
497 Method Calls
498 Some people like to "shift" off the invocant before running type
499 checks:
500
501 sub my_method {
502 my $self = shift;
503 state $check = compile_named(
504 haystack => ArrayRef,
505 needle => Int,
506 );
507 my $arg = $check->(@_);
508
509 return $arg->{haystack}[ $self->base_index + $arg->{needle} ];
510 }
511
512 $object->my_method(haystack => \@somelist, needle => 42);
513
514 If you're using positional parameters, there's really no harm in
515 including the invocant in the check:
516
517 sub my_method {
518 state $check = compile(Object, ArrayRef, Int);
519 my ($self, $arr, $ix) = $check->(@_);
520
521 return $arr->[ $self->base_index + $ix ];
522 }
523
524 $object->my_method(\@somelist, 42);
525
526 Some methods will be designed to be called as class methods rather than
527 instance methods. Remember to use "ClassName" instead of "Object" in
528 those cases.
529
530 Type::Params exports an additional keyword "Invocant" on request. This
531 gives you a type constraint which accepts classnames and blessed
532 objects.
533
534 use Type::Params qw( compile Invocant );
535
536 sub my_method {
537 state $check = compile(Invocant, ArrayRef, Int);
538 my ($self_or_class, $arr, $ix) = $check->(@_);
539
540 return $arr->[ $ix ];
541 }
542
543 There is no "coerce => 0"
544 If you give "compile" a type constraint which has coercions, then
545 $check will always coerce. It cannot be switched off.
546
547 Luckily, Type::Tiny gives you a very easy way to create a type
548 constraint without coercions from one that has coercions:
549
550 state $check = compile(
551 $RoundedInt->no_coercions,
552 $RoundedInt->minus_coercions(Num),
553 );
554
555 That's a Type::Tiny feature rather than a Type::Params feature though.
556
557 Extra Coercions
558 Type::Tiny provides an easy shortcut for adding coercions to a type
559 constraint:
560
561 # We want an arrayref, but accept a hashref and coerce it
562 state $check => compile(
563 ArrayRef->plus_coercions( HashRef, sub { [sort values %$_] } ),
564 );
565
566 Value Constraints
567 You may further constrain a parameter using "where":
568
569 state $check = compile(
570 Int->where('$_ % 2 == 0'), # even numbers only
571 );
572
573 This is also a Type::Tiny feature rather than a Type::Params feature.
574
575 Smarter Defaults
576 This works:
577
578 sub print_coloured {
579 state $check = compile(
580 Str,
581 Str, { default => "black" },
582 );
583
584 my ($text, $colour) = $check->(@_);
585
586 ...;
587 }
588
589 But so does this (and it might benchmark a little faster):
590
591 sub print_coloured {
592 state $check = compile(
593 Str,
594 Str, { optional => 1 },
595 );
596
597 my ($text, $colour) = $check->(@_);
598 $colour = "black" if @_ < 2;
599
600 ...;
601 }
602
603 Just because Type::Params now supports defaults, doesn't mean you can't
604 do it the old-fashioned way. The latter is more flexible. In the
605 example, we've used "if @_ < 2", but we could instead have done
606 something like:
607
608 $colour ||= "black";
609
610 Which would have defaulted $colour to "black" if it were the empty
611 string.
612
614 "PERL_TYPE_PARAMS_XS"
615 Affects the building of accessors for "compile_named_oo". If set to
616 true, will use Class::XSAccessor. If set to false, will use pure
617 Perl. If this environment variable does not exist, will use
618 Class::XSAccessor if it is available.
619
621 Params::Validate
622 Type::Params is not really a drop-in replacement for Params::Validate;
623 the API differs far too much to claim that. Yet it performs a similar
624 task, so it makes sense to compare them.
625
626 · Type::Params will tend to be faster if you've got a sub which is
627 called repeatedly, but may be a little slower than Params::Validate
628 for subs that are only called a few times. This is because it does
629 a bunch of work the first time your sub is called to make
630 subsequent calls a lot faster.
631
632 · Params::Validate doesn't appear to have a particularly natural way
633 of validating a mix of positional and named parameters.
634
635 · Type::Utils allows you to coerce parameters. For example, if you
636 expect a Path::Tiny object, you could coerce it from a string.
637
638 · If you are primarily writing object-oriented code, using Moose or
639 similar, and you are using Type::Tiny type constraints for your
640 attributes, then using Type::Params allows you to use the same
641 constraints for method calls.
642
643 · Type::Params comes bundled with Types::Standard, which provides a
644 much richer vocabulary of types than the type validation constants
645 that come with Params::Validate. For example, Types::Standard
646 provides constraints like "ArrayRef[Int]" (an arrayref of
647 integers), while the closest from Params::Validate is "ARRAYREF",
648 which you'd need to supplement with additional callbacks if you
649 wanted to check that the arrayref contained integers.
650
651 Whatsmore, Type::Params doesn't just work with Types::Standard, but
652 also any other Type::Tiny type constraints.
653
654 Params::ValidationCompiler
655 Params::ValidationCompiler does basically the same thing as
656 Type::Params.
657
658 · Params::ValidationCompiler and Type::Params are likely to perform
659 fairly similarly. In most cases, recent versions of Type::Params
660 seem to be slightly faster, but except in very trivial cases,
661 you're unlikely to notice the speed difference. Speed probably
662 shouldn't be a factor when choosing between them.
663
664 · Type::Params's syntax is more compact:
665
666 state $check = compile(Object, Optional[Int], slurpy ArrayRef);
667
668 Versus:
669
670 state $check = validation_for(
671 params => [
672 { type => Object },
673 { type => Int, optional => 1 },
674 { type => ArrayRef, slurpy => 1 },
675 ],
676 );
677
678 · Params::ValidationCompiler probably has slightly better exceptions.
679
681 Please report any bugs to
682 <http://rt.cpan.org/Dist/Display.html?Queue=Type-Tiny>.
683
685 Type::Tiny, Type::Coercion, Types::Standard.
686
688 Toby Inkster <tobyink@cpan.org>.
689
691 This software is copyright (c) 2013-2014, 2017-2019 by Toby Inkster.
692
693 This is free software; you can redistribute it and/or modify it under
694 the same terms as the Perl 5 programming language system itself.
695
697 THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
698 WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
699 MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
700
701
702
703perl v5.30.0 2019-07-26 Type::Params(3)