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

NAME

6       Type::Params - sub signature validation using Type::Tiny type
7       constraints and coercions
8

SYNOPSIS

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

STATUS

45       This module is covered by the Type-Tiny stability policy.
46

DESCRIPTION

48       This documents the details of the Type::Params package.
49       Type::Tiny::Manual is a better starting place if you're new.
50
51       Type::Params uses Type::Tiny constraints to validate the parameters to
52       a sub. It takes the slightly unorthodox approach of separating
53       validation into two stages:
54
55       1.  Compiling the parameter specification into a coderef; then
56
57       2.  Using the coderef to validate parameters.
58
59       The first stage is slow (it might take a couple of milliseconds), but
60       you only need to do it the first time the sub is called. The second
61       stage is fast; according to my benchmarks faster even than the XS
62       version of Params::Validate.
63

MODERN API

65       The modern API can be exported using:
66
67        use Type::Params -sigs;
68
69       Or:
70
71        use Type::Params -v2;
72
73       Or by requesting functions by name:
74
75        use Type::Params qw( signature signature_for );
76
77   signature( %spec )
78       The "signature" function takes a specification for your function's
79       signature and returns a coderef. You then call the coderef in list
80       context, passing @_ to it. The coderef will check, coerce, and apply
81       other procedures to the values, and return the tidied values, or die
82       with an error.
83
84       The usual way of using it is:
85
86        sub your_function {
87          state $signature = signature( ... );
88          my ( $arg1, $arg2, $arg3 ) = $signature->( @_ );
89
90          ...;
91        }
92
93       Perl allows a slightly archaic way of calling coderefs without using
94       parentheses, which may be slightly faster at the cost of being more
95       obscure:
96
97        sub your_function {
98          state $signature = signature( ... );
99          my ( $arg1, $arg2, $arg3 ) = &$signature;
100
101          ...;
102        }
103
104       If you need to support Perl 5.8, which didn't have the "state" keyword:
105
106        my $__your_function_sig;
107        sub your_function {
108          $__your_function_sig ||= signature( ... );
109          my ( $arg1, $arg2, $arg3 ) = $__your_function_sig->( @_ );
110
111          ...;
112        }
113
114       One important thing to note is how the signature is only compiled into
115       a coderef the first time your function gets called, and thereafter will
116       be reused.
117
118       Signature Specification Options
119
120       The signature specification is a hash which must contain either a
121       "positional", "named", or "multiple" key indicating whether your
122       function takes positional parameters, named parameters, or supports
123       multiple calling conventions, but may also include other options.
124
125       "positional" ArrayRef
126
127       This is conceptually a list of type constraints, one for each
128       positional parameter. For example, a signature for a function which
129       accepts two integers:
130
131        signature( positional => [ Int, Int ] )
132
133       However, each type constraint is optionally followed by a hashref of
134       options which affect that parameter. For example:
135
136        signature( positional => [
137          Int, { default => 40 },
138          Int, { default =>  2 },
139        ] )
140
141       Type constraints can instead be given as strings, which will be looked
142       up using "dwim_type" from Type::Utils.
143
144        signature( positional => [
145          'Int', { default => 40 },
146          'Int', { default =>  2 },
147        ] )
148
149       See the section below for more information on parameter options.
150
151       Optional parameters must follow required parameters, and can be
152       specified using either the Optional parameterizable type constraint,
153       the "optional" parameter option, or by providing a default.
154
155        signature( positional => [
156          Optional[Int],
157          Int, { optional => !!1 },
158          Int, { default  => 42 },
159        ] )
160
161       A single slurpy parameter may be provided at the end, using the Slurpy
162       parameterizable type constraint, or the "slurpy" parameter option:
163
164        signature( positional => [
165          Int,
166          Slurpy[ ArrayRef[Int] ],
167        ] )
168
169        signature( positional => [
170          Int,
171          ArrayRef[Int], { slurpy => !!1 },
172        ] )
173
174       The "positional" option can also be abbreviated to "pos".
175
176       So "signature( pos => [...] )" can be used instead of the longer
177       "signature( positional => [...] )".
178
179       If a signature uses positional parameters, the values are returned by
180       the coderef as a list:
181
182        sub add_numbers {
183          state $sig = signature( positional => [ Num, Num ] );
184          my ( $num1, $num2 ) = $sig->( @_ );
185
186          return $num1 + $num2;
187        }
188
189        say add_numbers( 2, 3 );   # says 5
190
191       "named" ArrayRef
192
193       This is conceptually a list of pairs of names and type constraints, one
194       name+type pair for each positional parameter. For example, a signature
195       for a function which accepts two integers:
196
197        signature( named => [ foo => Int, bar => Int ] )
198
199       However, each type constraint is optionally followed by a hashref of
200       options which affect that parameter. For example:
201
202        signature( named => [
203          foo => Int, { default => 40 },
204          bar => Int, { default =>  2 },
205        ] )
206
207       Type constraints can instead be given as strings, which will be looked
208       up using "dwim_type" from Type::Utils.
209
210        signature( named => [
211          foo => 'Int', { default => 40 },
212          bar => 'Int', { default =>  2 },
213        ] )
214
215       Optional and slurpy parameters are allowed, but unlike positional
216       parameters, they do not need to be at the end.
217
218       See the section below for more information on parameter options.
219
220       If a signature uses named parameters, the values are returned by the
221       coderef as an object:
222
223        sub add_numbers {
224          state $sig = signature( named => [ num1 => Num, num2 => Num ] );
225          my ( $arg ) = $sig->( @_ );
226
227          return $arg->num1 + $arg->num2;
228        }
229
230        say add_numbers(   num1 => 2, num2 => 3   );   # says 5
231        say add_numbers( { num1 => 2, num2 => 3 } );   # also says 5
232
233       "named_to_list" ArrayRef|Bool
234
235       The "named_to_list" option is ignored for signatures using positional
236       parameters, but for signatures using named parameters, allows them to
237       be returned in a list instead of as an object:
238
239        sub add_numbers {
240          state $sig = signature(
241            named         => [ num1 => Num, num2 => Num ],
242            named_to_list => !!1,
243          );
244          my ( $num1, $num2 ) = $sig->( @_ );
245
246          return $num1 + $num2;
247        }
248
249        say add_numbers(   num1 => 2, num2 => 3   );   # says 5
250        say add_numbers( { num1 => 2, num2 => 3 } );   # also says 5
251
252       You can think of "add_numbers" above as a function which takes named
253       parameters from the outside, but receives positional parameters on the
254       inside.
255
256       You can use an arrayref to specify the order the paramaters will be
257       returned in. (By default they are returned in the order they were
258       defined in.)
259
260        sub add_numbers {
261          state $sig = signature(
262            named         => [ num1 => Num, num2 => Num ],
263            named_to_list => [ qw( num2 num1 ) ],
264          );
265          my ( $num2, $num1 ) = $sig->( @_ );
266
267          return $num1 + $num2;
268        }
269
270       "head" Int|ArrayRef
271
272       "head" provides an additional list of non-optional, positional
273       parameters at the start of @_. This is often used for method calls. For
274       example, if you wish to define a signature for:
275
276        $object->my_method( foo => 123, bar => 456 );
277
278       You could write it as this:
279
280        sub my_method {
281          state $signature = signature(
282            head    => [ Object ],
283            named   => [ foo => Optional[Int], bar => Optional[Int] ],
284          );
285          my ( $self, $arg ) = $signature->( @_ );
286
287          ...;
288        }
289
290       If "head" is set as a number instead of an arrayref, it is the number
291       of additional arguments at the start:
292
293        sub my_method {
294          state $signature = signature(
295            head    => 1,
296            named   => [ foo => Optional[Int], bar => Optional[Int] ],
297          );
298          my ( $self, $arg ) = $signature->( @_ );
299
300          ...;
301       }
302
303       In this case, no type checking is performed on those additional
304       arguments; it is just checked that they exist.
305
306       "tail" Int|ArrayRef
307
308       A "tail" is like a "head" except that it is for arguments at the end of
309       @_.
310
311        sub my_method {
312          state $signature = signature(
313            head    => [ Object ],
314            named   => [ foo => Optional[Int], bar => Optional[Int] ],
315            tail    => [ CodeRef ],
316          );
317          my ( $self, $arg, $callback ) = $signature->( @_ );
318
319          ...;
320        }
321
322        $object->my_method( foo => 123, bar => 456, sub { ... } );
323
324       "method" Bool|TypeTiny
325
326       While "head" can be used for method signatures, a more declarative way
327       is to set "method => 1".
328
329       If you wish to be specific that this is an object method, intended to
330       be called on blessed objects only, then you may use "method => Object",
331       using the Object type from Types::Standard. If you wish to specify that
332       it's a class method, then use "method => Str", using the Str type from
333       Types::Standard. ("method => ClassName" is perhaps clearer, but it's a
334       slower check.)
335
336        sub my_method {
337          state $signature = signature(
338            method  => 1,
339            named   => [ foo => Optional[Int], bar => Optional[Int] ],
340          );
341          my ( $self, $arg ) = $signature->( @_ );
342
343          ...;
344        }
345
346       If "method" is true (or a type constraint) then any parameter defaults
347       which are coderefs will be called as methods.
348
349       "description" Str
350
351       This is the description of the coderef that will show up in stack
352       traces.  It defaults to "parameter validation for X" where X is the
353       caller sub name.  Usually the default will be fine.
354
355       "package" Str
356
357       The package of the sub whose paramaters we're supposed to be checking.
358       As well as showing up in stack traces, it's used by "dwim_type" if you
359       provide any type constraints as strings.
360
361       The default is probably fine, but if you're wrapping "signature" so
362       that you can check signatures on behalf of another package, you may
363       need to provide it.
364
365       "subname" Str
366
367       The name of the sub whose paramaters we're supposed to be checking.
368
369       The default is probably fine, but if you're wrapping "signature" so
370       that you can check signatures on behalf of another package, you may
371       need to provide it.
372
373       "caller_level" Int
374
375       If you're wrapping "signature" so that you can check signatures on
376       behalf of another package, then setting "caller_level" to 1 (or more,
377       depending on the level of wrapping!) may be an alternative to manually
378       setting the "package" and "subname".
379
380       "on_die" Maybe[CodeRef]
381
382       Usually when your coderef hits an error, it will throw an exception,
383       which is a blessed Error::TypeTiny object.
384
385       If you provide an "on_die" coderef, then instead the Error::TypeTiny
386       object will be passed to it. If the "on_die" coderef returns something,
387       then whatever it returns will be returned as your signature's
388       parameters.
389
390        sub add_numbers {
391          state $sig = signature(
392            positional => [ Num, Num ],
393            on_die     => sub {
394              my $error = shift;
395              print "Existential crisis: $error\n";
396              exit( 1 );
397            },
398          );
399          my ( $num1, $num2 ) = $sig->( @_ );
400
401          return $num1 + $num2;
402        }
403
404        say add_numbers();   # has an existential crisis
405
406       This is probably not very useful.
407
408       "goto_next" Bool|CodeLike
409
410       This can be used for chaining coderefs. If you understand "on_die",
411       it's more like an "on_live".
412
413        sub add_numbers {
414          state $sig = signature(
415            positional => [ Num, Num ],
416            goto_next  => sub {
417              my ( $num1, $num2 ) = @_;
418
419              return $num1 + $num2;
420            },
421          );
422
423          my $sum = $sig->( @_ );
424          return $sum;
425        }
426
427        say add_numbers( 2, 3 );   # says 5
428
429       If set to a true boolean instead of a coderef, has a slightly different
430       behaviour:
431
432        sub add_numbers {
433          state $sig = signature(
434            positional => [ Num, Num ],
435            goto_next  => !!1,
436          );
437
438          my $sum = $sig->(
439            sub { return $_[0] + $_[1] },
440            @_,
441          );
442          return $sum;
443        }
444
445        say add_numbers( 2, 3 );   # says 5
446
447       This looks strange. Why would this be useful? Well, it works nicely
448       with Moose's "around" keyword.
449
450        sub add_numbers {
451          return $_[1] + $_[2];
452        }
453
454        around add_numbers => signature(
455          method     => !!1,
456          positional => [ Num, Num ],
457          goto_next  => !!1,
458          package    => __PACKAGE__,
459          subname    => 'add_numbers',
460        );
461
462        say __PACKAGE__->add_numbers( 2, 3 );   # says 5
463
464       Note the way "around" works in Moose is that it expects a wrapper
465       coderef as its final argument. That wrapper coderef then expects to be
466       given a reference to the original function as its first parameter.
467
468       This can allow, for example, a role to provide a signature wrapping a
469       method defined in a class.
470
471       This is kind of complex, and you're unlikely to use it, but it's been
472       proven useful for tools that integrate Type::Params with Moose-like
473       method modifiers.
474
475       "strictness" Bool|Str
476
477       If you set "strictness" to a false value (0, undef, or the empty
478       string), then certain signature checks will simply never be done. The
479       initial check that there's the correct number of parameters, plus type
480       checks on parameters which don't coerce can be skipped.
481
482       If you set it to a true boolean (i.e. 1) or do not set it at all, then
483       these checks will always be done.
484
485       Alternatively, it may be set to the quoted fully-qualified name of a
486       Perl global variable or a constant, and that will be compiled into the
487       coderef as a condition to enable strict checks.
488
489        state $signature = signature(
490          strictness => '$::CHECK_TYPES',
491          positional => [ Int, ArrayRef ],
492        );
493
494        # Type checks are skipped
495        {
496          local $::CHECK_TYPES = 0;
497          my ( $number, $list ) = $signature->( {}, {} );
498        }
499
500        # Type checks are performed
501        {
502          local $::CHECK_TYPES = 1;
503          my ( $number, $list ) = $signature->( {}, {} );
504        }
505
506       A recommended use of this is with Devel::StrictMode.
507
508        use Devel::StrictMode qw( STRICT );
509
510        state $signature = signature(
511          strictness => STRICT,
512          positional => [ Int, ArrayRef ],
513        );
514
515       "multiple" ArrayRef
516
517       This option allows your signature to support multiple calling
518       conventions.  Each entry in the array is an alternative signature, as a
519       hashref:
520
521        state $signature = signature(
522          multiple => [
523            {
524              positional => [ ArrayRef, Int ],
525            },
526            {
527              named      => [ array => ArrayRef, index => Int ],
528              named_to_list => 1,
529            },
530          ],
531        );
532
533       That signature will allow your function to be called as:
534
535        your_function( $arr, $ix )
536        your_function( array => $arr, index => $ix )
537        your_function( { array => $arr, index => $ix } )
538
539       Sometimes the alternatives will return the parameters in a different
540       order:
541
542        state $signature = signature(
543          multiple => [
544            { positional => [ ArrayRef, Int ] },
545            { positional => [ Int, ArrayRef ] },
546          ],
547        );
548        my ( $xxx, $yyy ) = $signature->( @_ );
549
550       So how does your sub know whether $xxx or $yyy is the arrayref?  One
551       option is to use the "${^_TYPE_PARAMS_MULTISIG}" global variable which
552       will be set to the index of the signature which was used:
553
554        my @results = $signature->( @_ );
555        my ( $arr, $ix ) = ${^_TYPE_PARAMS_MULTISIG} == 1
556          ? reverse( @results )
557          : @results;
558
559       A neater solution is to use a "goto_next" coderef to re-order
560       alternative signature results into your preferred order:
561
562        state $signature = signature(
563          multiple => [
564            { positional => [ ArrayRef, Int ] },
565            { positional => [ Int, ArrayRef ], goto_next => sub { reverse @_ } },
566          ],
567        );
568        my ( $arr, $ix ) = $signature->( @_ );
569
570       While conceptally "multiple" is an arrayref of hashrefs, it is also
571       possible to use arrayrefs in the arrayref.
572
573        multiple => [
574          [ ArrayRef, Int ],
575          [ Int, ArrayRef ],
576        ]
577
578       When an arrayref is used like that, it is a shortcut for a positional
579       signature.
580
581       Coderefs may additionally be used:
582
583        state $signature = signature(
584          multiple => [
585            [ ArrayRef, Int ],
586            { positional => [ Int, ArrayRef ], goto_next => sub { reverse @_ } },
587            sub { ... },
588            sub { ... },
589          ],
590        );
591
592       The coderefs should be subs which return a list of parameters if they
593       succeed and throw an exception if they fail.
594
595       The following signatures are equivalent:
596
597        state $sig_1 = signature(
598          multiple => [
599            { method => 1, positional => [ ArrayRef, Int ] },
600            { method => 1, positional => [ Int, ArrayRef ] },
601          ],
602        );
603
604        state $sig_2 = signature(
605          method   => 1,
606          multiple => [
607            { positional => [ ArrayRef, Int ] },
608            { positional => [ Int, ArrayRef ] },
609          ],
610        );
611
612       The "multiple" option can also be abbreviated to "multi".
613
614       So "signature( multi => [...] )" can be used instead of the longer
615       "signature( multiple => [...] )". Three whole keystrokes saved!
616
617       (Note: in older releases of Type::Params, "${^_TYPE_PARAMS_MULTISIG}"
618       was called "${^TYPE_PARAMS_MULTISIG}". The latter name is deprecated,
619       and support for it will be removed in a future release of
620       Type::Params.)
621
622       "message" Str
623
624       Only used by "multiple" signatures. The error message to throw when no
625       signatures match.
626
627       "want_source" Bool
628
629       Instead of returning a coderef, return Perl source code string. Handy
630       for debugging.
631
632       "want_details" Bool
633
634       Instead of returning a coderef, return a hashref of stuff including the
635       coderef. This is mostly for people extending Type::Params and I won't
636       go into too many details about what else this hashref contains.
637
638       "bless" Bool|ClassName, "class" ClassName|ArrayRef, and "constructor"
639       Str
640
641       Named parameters are usually returned as a blessed object:
642
643        sub add_numbers {
644          state $sig = signature( named => [ num1 => Num, num2 => Num ] );
645          my ( $arg ) = $sig->( @_ );
646
647          return $arg->num1 + $arg->num2;
648        }
649
650       The class they are blessed into is one built on-the-fly by
651       Type::Params.  However, these three signature options allow you more
652       control over that process.
653
654       Firstly, if you set "bless => false" and do not set "class" or
655       "constructor", then $arg will just be an unblessed hashref.
656
657        sub add_numbers {
658          state $sig = signature(
659            named        => [ num1 => Num, num2 => Num ],
660            bless        => !!0,
661          );
662          my ( $arg ) = $sig->( @_ );
663
664          return $arg->{num1} + $arg->{num2};
665        }
666
667       This is a good speed boost, but having proper methods for each named
668       parameter is a helpful way to catch misspelled names.
669
670       If you wish to manually create a class instead of relying on
671       Type::Params generating one on-the-fly, you can do this:
672
673        package Params::For::AddNumbers {
674          sub num1 { return $_[0]{num1} }
675          sub num2 { return $_[0]{num2} }
676          sub sum {
677            my $self = shift;
678            return $self->num1 + $self->num2;
679          }
680        }
681
682        sub add_numbers {
683          state $sig = signature(
684            named        => [ num1 => Num, num2 => Num ],
685            bless        => 'Params::For::AddNumbers',
686          );
687          my ( $arg ) = $sig->( @_ );
688
689          return $arg->sum;
690        }
691
692       Note that "Params::For::AddNumbers" here doesn't include a "new" method
693       because Type::Params will directly do "bless( $arg, $opts{bless} )".
694
695       If you want Type::Params to use a proper constructor, you should use
696       the "class" option instead:
697
698        package Params::For::AddNumbers {
699          use Moo;
700          has [ 'num1', 'num2' ] => ( is => 'ro' );
701          sub sum {
702            my $self = shift;
703            return $self->num1 + $self->num2;
704          }
705        }
706
707        sub add_numbers {
708          state $sig = signature(
709            named        => [ num1 => Num, num2 => Num ],
710            class        => 'Params::For::AddNumbers',
711          );
712          my ( $arg ) = $sig->( @_ );
713
714          return $arg->sum;
715        }
716
717       If you wish to use a constructor named something other than "new", then
718       use:
719
720        state $sig = signature(
721          named        => [ num1 => Num, num2 => Num ],
722          class        => 'Params::For::AddNumbers',
723          constructor  => 'new_from_hashref',
724        );
725
726       Or as a shortcut:
727
728        state $sig = signature(
729          named        => [ num1 => Num, num2 => Num ],
730          class        => [ 'Params::For::AddNumbers', 'new_from_hashref' ],
731        );
732
733       It is doubtful you want to use any of these options, except "bless =>
734       false".
735
736       Parameter Options
737
738       In the parameter lists for the "positional" and "named" signature
739       options, each parameter may be followed by a hashref of options
740       specific to that parameter:
741
742        signature(
743          positional => [
744            Int, \%options_for_first_parameter,
745            Int, \%options_for_other_parameter,
746          ],
747          %more_options_for_signature,
748        );
749
750        signature(
751          named => [
752            foo => Int, \%options_for_foo,
753            bar => Int, \%options_for_bar,
754          ],
755          %more_options_for_signature,
756        );
757
758       The following options are supported for parameters.
759
760       "optional" Bool
761
762       An option called optional!
763
764       This makes a parameter optional:
765
766        sub add_nums {
767          state $sig = signature(
768            positional => [
769              Int,
770              Int,
771              Bool, { optional => !!1 },
772            ],
773          );
774
775          my ( $num1, $num2, $debug ) = $sig->( @_ );
776
777          my $sum = $num1 + $num2;
778          warn "$sum = $num1 + $num2" if $debug;
779
780          return $sum;
781        }
782
783        add_nums( 2, 3, 1 );   # prints warning
784        add_nums( 2, 3, 0 );   # no warning
785        add_nums( 2, 3    );   # no warning
786
787       Types::Standard also provides a Optional parameterizable type which may
788       be a neater way to do this:
789
790        state $sig = signature(
791          positional => [ Int, Int, Optional[Bool] ],
792        );
793
794       In signatures with positional parameters, any optional parameters must
795       be defined after non-optional parameters. The "tail" option provides a
796       workaround for required parameters at the end of @_.
797
798       In signatures with named parameters, the order of optional and non-
799       optional parameters is unimportant.
800
801       "slurpy" Bool
802
803       A signature may contain a single slurpy parameter, which mops up any
804       other arguments the caller provides your function.
805
806       In signatures with positional parameters, slurpy params must always
807       have some kind of ArrayRef or HashRef type constraint, must always
808       appear at the end of the list of positional parameters, and they work
809       like this:
810
811        sub add_nums {
812          state $sig = signature(
813            positional => [
814              Num,
815              ArrayRef[Num], { slurpy => !!1 },
816            ],
817          );
818          my ( $first_num, $other_nums ) = $sig->( @_ );
819
820          my $sum = $first_num;
821          $sum += $_ for @$other_nums;
822
823          return $sum;
824        }
825
826        say add_nums( 1 );            # says 1
827        say add_nums( 1, 2 );         # says 3
828        say add_nums( 1, 2, 3 );      # says 6
829        say add_nums( 1, 2, 3, 4 );   # says 10
830
831       In signatures with named parameters, slurpy params must always have
832       some kind of HashRef type constraint, and they work like this:
833
834        use builtin qw( true false );
835
836        sub process_data {
837          state $sig = signature(
838            method => true,
839            named  => [
840              input   => FileHandle,
841              output  => FileHandle,
842              flags   => HashRef[Bool], { slurpy => true },
843            ],
844          );
845          my ( $self, $arg ) = @_;
846          warn "Beginning data processing" if $arg->flags->{debug};
847
848          ...;
849        }
850
851        $widget->process_data(
852          input  => \*STDIN,
853          output => \*STDOUT,
854          debug  => true,
855        );
856
857       The Slurpy type constraint from Types::Standard may be used as a
858       shortcut to specify slurpy parameters:
859
860        signature(
861          positional => [ Num, Slurpy[ ArrayRef[Num] ] ],
862        )
863
864       The type Slurpy[Any] is handled specially and treated as a slurpy
865       ArrayRef in signatures with positional parameters, and a slurpy HashRef
866       in signatures with named parameters, but has some additional
867       optimizations for speed.
868
869       "default" CodeRef|ScalarRef|Ref|Str|Undef
870
871       A default may be provided for a parameter.
872
873        state $check = signature(
874          positional => [
875            Int,
876            Int, { default => "666" },
877            Int, { default => "999" },
878          ],
879        );
880
881       Supported defaults are any strings (including numerical ones), "undef",
882       and empty hashrefs and arrayrefs. Non-empty hashrefs and arrayrefs are
883       not allowed as defaults.
884
885       Alternatively, you may provide a coderef to generate a default value:
886
887        state $check = signature(
888          positional => [
889            Int,
890            Int, { default => sub { 6 * 111 } },
891            Int, { default => sub { 9 * 111 } },
892          ]
893        );
894
895       That coderef may generate any value, including non-empty arrayrefs and
896       non-empty hashrefs. For undef, simple strings, numbers, and empty
897       structures, avoiding using a coderef will make your parameter
898       processing faster.
899
900       Instead of a coderef, you can use a reference to a string of Perl
901       source code:
902
903        state $check = signature(
904          positional => [
905            Int,
906            Int, { default => \ '6 * 111' },
907            Int, { default => \ '9 * 111' },
908          ],
909        );
910
911       Defaults will be validated against the type constraint, and potentially
912       coerced.
913
914       Any parameter with a default will automatically be optional.
915
916       Note that having any defaults in a signature (even if they never end up
917       getting used) can slow it down, as Type::Params will need to build a
918       new array instead of just returning @_.
919
920       "coerce" Bool
921
922       Speaking of which, the "coerce" option allows you to indicate that a
923       value should be coerced into the correct type:
924
925        state $sig = signature(
926          positional => [
927            Int,
928            Int,
929            Bool, { coerce => true },
930          ],
931        );
932
933       Setting "coerce" to false will disable coercion.
934
935       If "coerce" is not specified, so is neither true nor false, then
936       coercion will be enabled if the type constraint has a coercion, and
937       disabled otherwise.
938
939       Note that having any coercions in a signature (even if they never end
940       up getting used) can slow it down, as Type::Params will need to build a
941       new array instead of just returning @_.
942
943       "clone" Bool
944
945       If this is set to true, it will deep clone incoming values via "dclone"
946       from Storable (a core module since Perl 5.7.3).
947
948       In the below example, $arr is a reference to a clone of @numbers, so
949       pushing additional numbers to it leaves @numbers unaffected.
950
951        sub foo {
952          state $check = signature(
953            positional => [
954              ArrayRef, { clone => 1 }
955            ],
956          );
957          my ( $arr ) = &$check;
958
959          push @$arr, 4, 5, 6;
960        }
961
962        my @numbers = ( 1, 2, 3 );
963        foo( \@numbers );
964
965        print "@numbers\n";  ## 1 2 3
966
967       Note that cloning will significantly slow down your signature.
968
969       "name" Str
970
971       This overrides the name of a named parameter. I don't know why you
972       would want to do that.
973
974       The following signature has two parameters: "foo" and "bar". The name
975       "fool" is completely ignored.
976
977        signature(
978          named => [
979            fool   => Int, { name => 'foo' },
980            bar    => Int,
981          ],
982        )
983
984       You can, however, also name positional parameters, which don't usually
985       have names.
986
987        signature(
988          positional => [
989            Int, { name => 'foo' },
990            Int, { name => 'bar' },
991          ],
992        )
993
994       The names of positional parameters are not really used for anything at
995       the moment, but may be incorporated into error messages or similar in
996       the future.
997
998       "getter" Str
999
1000       For signatures with named parameters, specifies the method name used to
1001       retrieve this parameter's value from the $arg object.
1002
1003        sub process_data {
1004          state $sig = signature(
1005            method => true,
1006            named  => [
1007              input   => FileHandle,    { getter => 'in' },
1008              output  => FileHandle,    { getter => 'out' },
1009              flags   => HashRef[Bool], { slurpy => true },
1010            ],
1011          );
1012          my ( $self, $arg ) = @_;
1013          warn "Beginning data processing" if $arg->flags->{debug};
1014
1015          my ( $in, $out ) = ( $arg->in, $arg->out );
1016          ...;
1017        }
1018
1019        $widget->process_data(
1020          input  => \*STDIN,
1021          output => \*STDOUT,
1022          debug  => true,
1023        );
1024
1025       Ignored by signatures with positional parameters.
1026
1027       "predicate" Str
1028
1029       The $arg object provided by signatures with named parameters will also
1030       include "has" methods for any optional arguments.  For example:
1031
1032        state $sig = signature(
1033          method => true,
1034          named  => [
1035            input   => Optional[ FileHandle ],
1036            output  => Optional[ FileHandle ],
1037            flags   => Slurpy[ HashRef[Bool] ],
1038          ],
1039        );
1040        my ( $self, $arg ) = $sig->( @_ );
1041
1042        if ( $self->has_input and $self->has_output ) {
1043          ...;
1044        }
1045
1046       Setting a "predicate" option allows you to choose a different name for
1047       this method.
1048
1049       It is also possible to set a "predicate" for non-optional parameters,
1050       which don't normally get a "has" method.
1051
1052       Ignored by signatures with positional parameters.
1053
1054       "alias" Str|ArrayRef[Str]
1055
1056       A list of alternative names for the parameter, or a single alternative
1057       name.
1058
1059        sub add_numbers {
1060          state $sig = signature(
1061            named => [
1062              first_number   => Int, { alias => [ 'x' ] },
1063              second_number  => Int, { alias =>   'y'   },
1064            ],
1065          );
1066          my ( $arg ) = $sig->( @_ );
1067
1068          return $arg->first_number + $arg->second_number;
1069        }
1070
1071        say add_numbers( first_number => 40, second_number => 2 );  # 42
1072        say add_numbers( x            => 40, y             => 2 );  # 42
1073        say add_numbers( first_number => 40, y             => 2 );  # 42
1074        say add_numbers( first_number => 40, x => 1, y => 2 );      # dies!
1075
1076       Ignored by signatures with positional parameters.
1077
1078       "strictness" Bool|Str
1079
1080       Overrides the signature option "strictness" on a per-parameter basis.
1081
1082   "signature_for $function_name => ( %spec )"
1083       Like "signature", but instead of returning a coderef, wraps an existing
1084       function, so you don't need to deal with the mechanics of generating
1085       the signature at run-time, calling it, and extracting the returned
1086       values.
1087
1088       The following three examples are roughly equivalent:
1089
1090        sub add_nums {
1091          state $signature = signature(
1092            positional => [ Num, Num ],
1093          );
1094          my ( $x, $y ) = $signature->( @_ );
1095
1096          return $x + $y;
1097        }
1098
1099       Or:
1100
1101        signature_for add_nums => (
1102          positional => [ Num, Num ],
1103        );
1104
1105        sub add_nums {
1106          my ( $x, $y ) = @_;
1107
1108          return $x + $y;
1109        }
1110
1111       Or since Perl 5.20:
1112
1113        signature_for add_nums => (
1114          positional => [ Num, Num ],
1115        );
1116
1117        sub add_nums ( $x, $y ) {
1118          return $x + $y;
1119        }
1120
1121       The "signature_for" keyword turns "signature" inside-out.
1122
1123       The same signature specification options are supported, with the
1124       exception of "want_source", "want_details", and "goto_next" which will
1125       not work.  (If using the "multiple" option, then "goto_next" is still
1126       supported in the nested signatures.)
1127
1128       If you are providing a signature for a sub in another package, then
1129       "signature_for "Some::Package::some_sub" => ( ... )" will work, as will
1130       "signature_for some_sub => ( package => "Some::Package", ... )".  If
1131       "method" is true, then "signature_for" will respect inheritance when
1132       determining which sub to wrap. "signature_for" will not be able to find
1133       lexical subs, so use "signature" within the sub instead.
1134
1135       The "goto_next" option is what "signature_for" uses to "connect" the
1136       signature to the body of the sub, so do not use it unless you
1137       understand the consequences and want to override the normal behaviour.
1138
1139       If the sub being wrapped cannot be found, then "signature_for" will
1140       usually throw an error. If you want it to "work" in this situation, use
1141       the "fallback" option. "fallback => \&alternative_coderef_to_wrap" will
1142       instead wrap a different coderef if the original cannot be found.
1143       "fallback => 1" is a shortcut for "fallback => sub {}".  An example
1144       where this might be useful is if you're adding signatures to methods
1145       which are inherited from a parent class, but you are not 100% confident
1146       will exist (perhaps dependent on the version of the parent class).
1147
1148        signature_for add_nums => (
1149          positional => [ Num, Num ],
1150          fallback   => sub { $_[0] + $_[1] },
1151        );
1152
1153       "signature_for( \@functions, %opts )" is a useful shortcut if you have
1154       multiple functions with the same signature.
1155
1156        signature_for [ 'add_nums', 'subtract_nums' ] => (
1157          positional => [ Num, Num ],
1158        );
1159

LEGACY API

1161       The following functions were the API prior to Type::Params v2. They are
1162       still supported, but their use is now discouraged.
1163
1164       If you don't provide an import list at all, you will import "compile"
1165       and "compile_named":
1166
1167        use Type::Params;
1168
1169       This does the same:
1170
1171         use Type::Params -v1;
1172
1173       The following exports "compile", "compile_named", and
1174       "compile_named_oo":
1175
1176        use Type::Params -compile;
1177
1178       The following exports "wrap_subs" and "wrap_methods":
1179
1180        use Type::Params -wrap;
1181
1182   compile( @pos_params )
1183       Equivalent to "signature( positional => \@pos_params )".
1184
1185       "compile( \%spec, @pos_params )" is equivalent to "signature( %spec,
1186       positional => \@pos_params )".
1187
1188   compile_named( @named_params )
1189       Equivalent to "signature( bless => 0, named => \@named_params )".
1190
1191       "compile_named( \%spec, @named_params )" is equivalent to "signature(
1192       bless => 0, %spec, named => \@named_params )".
1193
1194   compile_named_oo( @named_params )
1195       Equivalent to "signature( bless => 1, named => \@named_params )".
1196
1197       "compile_named_oo( \%spec, @named_params )" is equivalent to
1198       "signature( bless => 1, %spec, named => \@named_params )".
1199
1200   "validate( \@args, @pos_params )"
1201       Equivalent to "signature( positional => \@pos_params )->( @args )".
1202
1203       The "validate" function has never been recommended, and is not exported
1204       unless requested by name.
1205
1206   "validate_named( \@args, @named_params )"
1207       Equivalent to "signature( bless => 0, named => \@named_params )->(
1208       @args )".
1209
1210       The "validate_named" function has never been recommended, and is not
1211       exported unless requested by name.
1212
1213   "wrap_subs( func1 => \@params1, func2 => \@params2, ... )"
1214       Equivalent to:
1215
1216        signature_for func1 => ( positional => \@params1 );
1217        signature_for func2 => ( positional => \@params2 );
1218
1219       One slight difference is that instead of arrayrefs, you can provide the
1220       output of one of the "compile" functions:
1221
1222        wrap_subs( func1 => compile_named( @params1 ) );
1223
1224       "wrap_subs" is not exported unless requested by name.
1225
1226   "wrap_methods( func1 => \@params1, func2 => \@params2, ... )"
1227       Equivalent to:
1228
1229        signature_for func1 => ( method => 1, positional => \@params1 );
1230        signature_for func2 => ( method => 1, positional => \@params2 );
1231
1232       One slight difference is that instead of arrayrefs, you can provide the
1233       output of one of the "compile" functions:
1234
1235         wrap_methods( func1 => compile_named( @params1 ) );
1236
1237       "wrap_methods" is not exported unless requested by name.
1238
1239   multisig( @alternatives )
1240       Equivalent to:
1241
1242         signature( multiple => \@alternatives )
1243
1244       "multisig( \%spec, @alternatives )" is equivalent to "signature( %spec,
1245       multiple => \@alternatives )".
1246

TYPE CONSTRAINTS

1248       Although Type::Params is not a real type library, it exports two type
1249       constraints. Their use is no longer recommended.
1250
1251   Invocant
1252       Type::Params exports a type Invocant on request. This gives you a type
1253       constraint which accepts classnames and blessed objects.
1254
1255        use Type::Params qw( compile Invocant );
1256
1257        sub my_method {
1258          state $check = signature(
1259            method     => Invocant,
1260            positional => [ ArrayRef, Int ],
1261          );
1262          my ($self_or_class, $arr, $ix) = $check->(@_);
1263
1264          return $arr->[ $ix ];
1265        }
1266
1267       "Invocant" is not exported unless requested by name.
1268
1269       Recommendation: use Defined from Types::Standard instead.
1270
1271   ArgsObject
1272       Type::Params exports a parameterizable type constraint ArgsObject.  It
1273       accepts the kinds of objects returned by signature checks for named
1274       parameters.
1275
1276         package Foo {
1277           use Moo;
1278           use Type::Params 'ArgsObject';
1279
1280           has args => (
1281             is  => 'ro',
1282             isa => ArgsObject['Bar::bar'],
1283           );
1284         }
1285
1286         package Bar {
1287           use Types::Standard -types;
1288           use Type::Params 'signature';
1289
1290           sub bar {
1291             state $check = signature(
1292               named => [
1293                 xxx => Int,
1294                 yyy => ArrayRef,
1295               ],
1296             );
1297             my ( $got ) = $check->( @_ );
1298
1299             return 'Foo'->new( args => $got );
1300           }
1301         }
1302
1303         Bar::bar( xxx => 42, yyy => [] );
1304
1305       The parameter "Bar::bar" refers to the caller when the check is
1306       compiled, rather than when the parameters are checked.
1307
1308       "ArgsObject" is not exported unless requested by name.
1309
1310       Recommendation: use Object from Types::Standard instead.
1311

ENVIRONMENT

1313       "PERL_TYPE_PARAMS_XS"
1314           Affects the building of accessors for $arg objects. If set to true,
1315           will use Class::XSAccessor. If set to false, will use pure Perl. If
1316           this environment variable does not exist, will use
1317           Class::XSAccessor.
1318
1319           If Class::XSAccessor is not installed or is too old, pure Perl will
1320           always be used as a fallback.
1321

BUGS

1323       Please report any bugs to
1324       <https://github.com/tobyink/p5-type-tiny/issues>.
1325

SEE ALSO

1327       The Type::Tiny homepage <https://typetiny.toby.ink/>.
1328
1329       Type::Tiny, Type::Coercion, Types::Standard.
1330

AUTHOR

1332       Toby Inkster <tobyink@cpan.org>.
1333
1335       This software is copyright (c) 2013-2014, 2017-2023 by Toby Inkster.
1336
1337       This is free software; you can redistribute it and/or modify it under
1338       the same terms as the Perl 5 programming language system itself.
1339

DISCLAIMER OF WARRANTIES

1341       THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
1342       WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
1343       MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
1344
1345
1346
1347perl v5.36.0                      2023-04-24                   Type::Params(3)
Impressum