1Function::Parameters(3)User Contributed Perl DocumentatioFnunction::Parameters(3)
2
3
4
6 Function::Parameters - define functions and methods with parameter
7 lists ("subroutine signatures")
8
10 use Function::Parameters;
11
12 # plain function
13 fun foo($x, $y, $z = 5) {
14 return $x + $y + $z;
15 }
16 print foo(1, 2), "\n"; # 8
17
18 # method with implicit $self
19 method bar($label, $n) {
20 return "$label: " . ($n * $self->scale);
21 }
22
23 # named arguments: order doesn't matter in the call
24 fun create_point(:$x, :$y, :$color) {
25 print "creating a $color point at ($x, $y)\n";
26 }
27 create_point(
28 color => "red",
29 x => 10,
30 y => 5,
31 );
32
33 package Derived {
34 use Function::Parameters qw(:std :modifiers);
35 use Moo;
36
37 extends 'Base';
38
39 has 'go_big' => (
40 is => 'ro',
41 );
42
43 # "around" method with implicit $orig and $self
44 around size() {
45 return $self->$orig() * 2 if $self->go_big;
46 return $self->$orig();
47 }
48 }
49
51 This module provides two new keywords, "fun" and "method", for defining
52 functions and methods with parameter lists. At minimum this saves you
53 from having to unpack @_ manually, but this module can do much more for
54 you.
55
56 The parameter lists provided by this module are similar to the
57 "signatures" feature available in perl v5.20+. However, this module
58 supports all perl versions starting from v5.14 and it offers far more
59 features than core signatures. The downside is that you need a C
60 compiler if you want to install it from source, as it uses Perl's
61 keyword plugin API in order to work reliably without requiring a source
62 filter.
63
64 Default functionality
65 This module is a lexically scoped pragma: If you "use
66 Function::Parameters" inside a block or file, the keywords won't be
67 available outside of that block or file.
68
69 You can also disable "Function::Parameters" within a block:
70
71 {
72 no Function::Parameters; # disable all keywords
73 ...
74 }
75
76 Or explicitly list the keywords you want to disable:
77
78 {
79 no Function::Parameters qw(method);
80 # 'method' is a normal identifier here
81 ...
82 }
83
84 You can also explicitly list the keywords you want to enable:
85
86 use Function::Parameters qw(fun); # provides 'fun' but not 'method'
87 use Function::Parameters qw(method); # provides 'method' but not 'fun'
88
89 Simple parameter lists
90
91 By default you get two keywords, "fun" and "method" (but see
92 "Customizing and extending" below). "fun" is very similar to "sub". You
93 can use it to define both named and anonymous functions:
94
95 fun left_pad($str, $n) {
96 return sprintf '%*s', $n, $str;
97 }
98
99 print left_pad("hello", 10), "\n";
100
101 my $twice = fun ($x) { $x * 2 };
102 print $twice->(21), "\n";
103
104 In the simplest case the parameter list is just a comma-separated list
105 of zero or more scalar variables (enclosed in parentheses, following
106 the function name, if any).
107
108 "Function::Parameters" automatically validates the arguments your
109 function is called with. If the number of arguments doesn't match the
110 parameter list, an exception is thrown.
111
112 Apart from that, the parameter variables are defined and initialized as
113 if by:
114
115 sub left_pad {
116 sub left_pad;
117 my ($str, $n) = @_;
118 ...
119 }
120
121 In particular, @_ is still available in functions defined by "fun" and
122 holds the original argument list.
123
124 The inner "sub left_pad;" declaration is intended to illustrate that
125 the name of the function being defined is in scope in its own body,
126 meaning you can call it recursively without having to use parentheses:
127
128 fun fac($n) {
129 return 1 if $n < 2;
130 return $n * fac $n - 1;
131 }
132
133 In a normal "sub" the last line would have had to be written "return $n
134 * fac($n - 1);".
135
136 "method" is almost the same as "fun" but automatically creates a $self
137 variable as the first parameter (which is removed from @_):
138
139 method foo($x, $y) {
140 ...
141 }
142
143 # works like:
144 sub foo :method {
145 my $self = shift;
146 my ($x, $y) = @_;
147 ...
148 }
149
150 As you can see, the ":method" attribute is also added automatically
151 (see "method" in attributes for details).
152
153 In some cases (e.g. class methods) $self is not the best name for the
154 invocant of the method. You can override it on a case-by-case basis by
155 putting a variable name followed by a ":" (colon) as the first thing in
156 the parameter list:
157
158 method new($class: $x, $y) {
159 return bless { x => $x, y => $y }, $class;
160 }
161
162 Here the invocant is named $class, not $self. It looks a bit weird but
163 still works the same way if the remaining parameter list is empty:
164
165 method from_env($class:) {
166 return $class->new($ENV{x}, $ENV{y});
167 }
168
169 Default arguments
170
171 (Most of the following examples use "fun" only. Unless specified
172 otherwise, everything applies to "method" as well.)
173
174 You can make some arguments optional by giving them default values.
175
176 fun passthrough($x, $y //= 42, $z = []) {
177 return ($x, $y, $z);
178 }
179
180 In this example the first parameter $x is required, but $y and $z are
181 optional.
182
183 passthrough('a', 'b', 'c', 'd') # error: Too many arguments
184 passthrough('a', 'b', 'c') # returns ('a', 'b', 'c')
185 passthrough('a', 'b', undef) # returns ('a', 'b', undef)
186 passthrough('a', 'b') # returns ('a', 'b', [])
187 passthrough('a', undef) # returns ('a', 42, [])
188 passthrough('a', undef, 'c') # returns ('a', 42, 'c')
189 passthrough('a') # returns ('a', 42, [])
190 passthrough() # error: Too few arguments
191
192 Default arguments specified with "=" are evaluated whenever a
193 corresponding real argument is not passed in by the caller. "undef"
194 counts as a real argument; you can't use the default value for
195 parameter N and still pass a value for parameter N+1.
196
197 Default arguments specified with "//=" are evaluated whenever a
198 corresponding real argument is not passed in or when that argument is
199 "undef". That is, passing in "undef" to a "//=" parameter lets you
200 explicitly request the default.
201
202 Both "=" and "//=" default arguments can be mixed freely in the same
203 parameter list.
204
205 "$z = []" means each call that doesn't pass a third argument gets a new
206 array reference (they're not shared between calls).
207
208 Default arguments are evaluated as part of the function body, allowing
209 for silliness such as:
210
211 fun weird($name = return "nope") {
212 print "Hello, $name!\n";
213 return $name;
214 }
215
216 weird("Larry"); # prints "Hello, Larry!" and returns "Larry"
217 weird(); # returns "nope" immediately; function body doesn't run
218
219 Preceding parameters are in scope for default arguments:
220
221 fun dynamic_default($x, $y = length $x) {
222 return "$x/$y";
223 }
224
225 dynamic_default("hello", 0) # returns "hello/0"
226 dynamic_default("hello") # returns "hello/5"
227 dynamic_default("abc") # returns "abc/3"
228
229 If you just want to make a parameter optional without giving it a
230 special value, write "$param = undef". There is a special shortcut
231 syntax for this case: "$param = undef" can also be written "$param ="
232 (with no following expression).
233
234 fun foo($x = undef, $y = undef, $z = undef) {
235 # three arguments, all optional
236 ...
237 }
238
239 fun foo($x=, $y=, $z=) {
240 # shorter syntax, same meaning
241 ...
242 }
243
244 Optional parameters must come at the end. It is not possible to have a
245 required parameter after an optional one.
246
247 Slurpy/rest parameters
248
249 The last parameter of a function or method can be an array. This lets
250 you slurp up any number of arguments the caller passes (0 or more).
251
252 fun scale($factor, @values) {
253 return map { $_ * $factor } @values;
254 }
255
256 scale(10, 1 .. 4) # returns (10, 20, 30, 40)
257 scale(10) # returns ()
258
259 You can also use a hash, but then the number of arguments has to be
260 even.
261
262 Named parameters
263
264 As soon as your functions take more than three arguments, it gets
265 harder to keep track of which argument means what:
266
267 foo($handle, $w, $h * 2 + 15, 1, 24, 'icon');
268 # what do these arguments mean?
269
270 "Function::Parameters" offers an alternative for these kinds of
271 situations in the form of named parameters. Unlike the parameters
272 described previously, which are identified by position, these
273 parameters are identified by name:
274
275 fun create_point(:$x, :$y, :$color) {
276 ...
277 }
278
279 # Case 1
280 create_point(
281 x => 50,
282 y => 50,
283 color => 0xff_00_00,
284 );
285
286 To create a named parameter, put a ":" (colon) in front of it in the
287 parameter list. When the function is called, the arguments have to be
288 supplied in the form of a hash initializer (a list of alternating
289 keys/values). As with a hash, the order of key/value pairs doesn't
290 matter (except in the case of duplicate keys, where the last occurrence
291 wins):
292
293 # Case 2
294 create_point(
295 color => 0xff_00_00,
296 x => 50,
297 y => 50,
298 );
299
300 # Case 3
301 create_point(
302 x => 200,
303 color => 0x12_34_56,
304 color => 0xff_00_00,
305 x => 50,
306 y => 50,
307 );
308
309 Case 1, Case 2, and Case 3 all mean the same thing.
310
311 As with positional parameters, you can make named parameters optional
312 by supplying a default argument with "=" or "//=":
313
314 # use default if no 'color' key exists in the argument list
315 fun create_point(:$x, :$y, :$color = 0x00_00_00) {
316 ...
317 }
318
319 create_point(x => 0, y => 64) # color => 0x00_00_00 is implicit
320
321 Or:
322
323 # use default if 'color' value is not defined
324 fun create_point(:$x, :$y, :$color //= 0x00_00_00) {
325 ...
326 }
327
328 create_point(x => 0, y => 64, color => undef) # color => 0x00_00_00 is implicit
329
330 If you want to accept any key/value pairs, you can add a rest parameter
331 (hashes are particularly useful):
332
333 fun accept_all_keys(:$name, :$age, %rest) {
334 ...
335 }
336
337 accept_all_keys(
338 age => 42,
339 gender => 2,
340 name => "Jamie",
341 marbles => [],
342 );
343 # $name = "Jamie";
344 # $age = 42;
345 # %rest = (
346 # gender => 2,
347 # marbles => [],
348 # );
349
350 You can combine positional and named parameters, but all positional
351 parameters have to come first:
352
353 method output(
354 $data,
355 :$handle = $self->output_handle,
356 :$separator = $self->separator,
357 :$quote_fields = 0,
358 ) {
359 ...
360 }
361
362 $obj->output(["greetings", "from", "space"]);
363 $obj->output(
364 ["a", "random", "example"],
365 quote_fields => 1,
366 separator => ";",
367 );
368
369 Unnamed parameters
370
371 If your function doesn't use a particular parameter at all, you can
372 omit its name and just write a sigil in the parameter list:
373
374 register_callback('click', fun ($target, $) {
375 ...
376 });
377
378 Here we're calling a hypothetical "register_callback" function that
379 registers our coderef to be called in response to a "click" event. It
380 will pass two arguments to the click handler, but the coderef only
381 cares about the first one ($target). The second parameter doesn't even
382 get a name (just a sigil, "$"). This marks it as unused.
383
384 This case typically occurs when your functions have to conform to an
385 externally imposed interface, e.g. because they're called by someone
386 else. It can happen with callbacks or methods that don't need all of
387 the arguments they get.
388
389 You can use unnamed slurpy parameters to accept and ignore all
390 following arguments. In particular, "fun foo(@)" is a lot like "sub
391 foo" in that it accepts and ignores any number of arguments (and just
392 leaves them in @_).
393
394 Type constraints
395
396 It is possible to automatically check the types of arguments passed to
397 your function. There are two ways to do this.
398
399 1.
400 use Types::Standard qw(Str Int ArrayRef);
401
402 fun foo(Str $label, ArrayRef[Int] $counts) {
403 ...
404 }
405
406 In this variant you simply put the name of a type in front of a
407 parameter. The way this works is that "Function::Parameters" parses
408 the type using a restrictive set of rules:
409
410 • A type is a simplified expression that only uses "(", ")", "|",
411 "&", "/", "~", and simple types, except the first character
412 cannot be "(" (see syntax #2 below). The relative operator
413 precedence is as in Perl; see perlop.
414
415 • "(" ")" can be used for grouping, but have no effect otherwise.
416
417 • "~" (highest precedence) is a unary prefix operator meant for
418 complementary types (as provided by Type::Tiny).
419
420 • "/" is a binary infix operator meant for alternative types (as
421 provided by Type::Tiny).
422
423 • "&" is a binary infix operator meant for intersection types (as
424 provided by Type::Tiny).
425
426 • "|" (lowest precedence) is a binary infix operator meant for
427 union types (as provided by basically everyone doing type
428 constraints, including Moose (see "TYPE UNIONS" in
429 Moose::Manual::Types and MooseX::Types) and Type::Tiny).
430
431 • A simple type is an identifier, optionally followed by a list
432 of one or more types, separated by "," (comma), enclosed in "["
433 "]" (square brackets).
434
435 "Function::Parameters" then resolves simple types by looking for
436 functions of the same name in your current package. A type
437 specification like "Str | ArrayRef[Int]" ends up running the Perl
438 code "Str() | ArrayRef([Int()])" (at compile time, while the
439 function definition is being processed). In other words,
440 "Function::Parameters" doesn't support any types natively; it
441 simply uses whatever is in scope.
442
443 You don't have to define these type constraints yourself; you can
444 import them from a type library such as Types::Standard or
445 MooseX::Types::Moose.
446
447 The only requirement is that the returned value (here referred to
448 as $tc, for "type constraint") is an object that provides
449 "$tc->check($value)" and "$tc->get_message($value)" methods.
450 "check" is called to determine whether a particular value is valid;
451 it should return a true or false value. "get_message" is called on
452 values that fail the "check" test; it should return a string that
453 describes the error.
454
455 Type constraints can optionally support two additional features:
456
457 • Coercion. If the "$tc->has_coercion" method exists and returns
458 a true value, every incoming argument is automatically
459 transformed by "$value = $tc->coerce($value)" before being
460 type-checked.
461
462 • Inlining. If the "$tc->can_be_inlined" method exists and
463 returns a true value, the call to "$tc->check($value)" is
464 automatically replaced by the code returned (in string form)
465 from "$tc->inline_check('$value')". (For compatibility with
466 Moose, if $tc has no "inline_check" method,
467 "$tc->_inline_check('$value')" is used instead.)
468
469 2.
470 my ($my_type, $some_other_type);
471 BEGIN {
472 $my_type = Some::Constraint::Class->new;
473 $some_other_type = Some::Other::Class->new;
474 }
475
476 fun foo(($my_type) $label, ($some_other_type) $counts) {
477 ...
478 }
479
480 In this variant you enclose an arbitrary Perl expression in "(" ")"
481 (parentheses) and put it in front of a parameter. This expression
482 is evaluated at compile time and must return a type constraint
483 object as described above. (If you use variables here, make sure
484 they're defined at compile time.)
485
486 Method modifiers
487
488 "Function::Parameters" has support for method modifiers as provided by
489 Moo or Moose. They're not exported by default, so you have to say
490
491 use Function::Parameters qw(:modifiers);
492
493 to get them. This line gives you method modifiers only; "fun" and
494 "method" are not defined. To get both the standard keywords and method
495 modifiers, you can either write two "use" lines:
496
497 use Function::Parameters;
498 use Function::Parameters qw(:modifiers);
499
500 or explicitly list the keywords you want:
501
502 use Function::Parameters qw(fun method :modifiers);
503
504 or add the ":std" import tag (which gives you the default import
505 behavior):
506
507 use Function::Parameters qw(:std :modifiers);
508
509 This defines the following additional keywords: "before", "after",
510 "around", "augment", "override". These work mostly like "method", but
511 they don't install the function into your package themselves. Instead
512 they invoke whatever "before", "after", "around", "augment", or
513 "override" function (respectively) is in scope to do the job.
514
515 before foo($x, $y, $z) {
516 ...
517 }
518
519 works like
520
521 &before('foo', method ($x, $y, $z) {
522 ...
523 });
524
525 "after", "augment", and "override" work the same way.
526
527 "around" is slightly different: Instead of shifting off the first
528 element of @_ into $self (as "method" does), it shifts off two values:
529
530 around foo($x, $y, $z) {
531 ...
532 }
533
534 works like
535
536 &around('foo', sub :method {
537 my $orig = shift;
538 my $self = shift;
539 my ($x, $y, $z) = @_;
540 ...
541 });
542
543 (except you also get the usual "Function::Parameters" features such as
544 checking the number of arguments, etc).
545
546 $orig and $self both count as invocants and you can override their
547 names like this:
548
549 around foo($original, $object: $x, $y, $z) {
550 # $original is a reference to the wrapped method;
551 # $object is the object we're being called on
552 ...
553 }
554
555 If you use ":" to pick your own invocant names in the parameter list of
556 "around", you must specify exactly two variables.
557
558 These modifiers also differ from "fun" and "method" (and "sub") in that
559 they require a function name (there are no anonymous method modifiers)
560 and they take effect at runtime, not compile time. When you say "fun
561 foo() {}", the "foo" function is defined right after the closing "}" of
562 the function body is parsed. But with e.g. "before foo() {}", the
563 declaration becomes a normal function call (to the "before" function in
564 the current package), which is performed at runtime.
565
566 Prototypes and attributes
567
568 You can specify attributes (see "Subroutine Attributes" in perlsub) for
569 your functions using the usual syntax:
570
571 fun deref($x) :lvalue {
572 ${$x}
573 }
574
575 my $silly;
576 deref(\$silly) = 42;
577
578 To specify a prototype (see "Prototypes" in perlsub), use the
579 "prototype" attribute:
580
581 fun mypush($aref, @values) :prototype(\@@) {
582 push @{$aref}, @values;
583 }
584
585 Introspection
586
587 The function "Function::Parameters::info" lets you introspect parameter
588 lists at runtime. It is not exported, so you have to call it by its
589 full name.
590
591 It takes a reference to a function and returns either "undef" (if it
592 knows nothing about the function) or an object that describes the
593 parameter list of the given function. See Function::Parameters::Info
594 for details.
595
596 Customizing and extending
597 Wrapping "Function::Parameters"
598
599 Due to its nature as a lexical pragma, importing from
600 "Function::Parameters" always affects the scope that is currently being
601 compiled. If you want to write a wrapper module that enables
602 "Function::Parameters" automatically, just call
603 "Function::Parameters->import" from your own "import" method (and
604 "Function::Parameters->unimport" from your "unimport", as required).
605
606 Gory details of importing
607
608 At the lowest layer "use Function::Parameters ..." takes a list of one
609 or more hash references. Each key is a keyword to be defined as
610 specified by the corresponding value, which must be another hash
611 reference containing configuration options.
612
613 use Function::Parameters
614 {
615 keyword_1 => { ... },
616 keyword_2 => { ... },
617 },
618 {
619 keyword_3 => { ... },
620 };
621
622 If you don't specify a particular option, its default value is used.
623 The available configuration options are:
624
625 "attributes"
626 (string) The attributes that every function declared with this
627 keyword should have (in the form of source code, with a leading
628 ":").
629
630 Default: nothing
631
632 "check_argument_count"
633 (boolean) Whether functions declared with this keyword should check
634 how many arguments they are called with. If false, omitting a
635 required argument sets it to "undef" and excess arguments are
636 silently ignored. If true, an exception is thrown if too few or too
637 many arguments are passed.
638
639 Default: 1
640
641 "check_argument_types"
642 (boolean) Whether functions declared with this keyword should check
643 the types of the arguments they are called with. If false, type
644 constraints are parsed but silently ignored. If true, an exception
645 is thrown if an argument fails a type check.
646
647 Default: 1
648
649 "default_arguments"
650 (boolean) Whether functions declared with this keyword should allow
651 default arguments in their parameter list. If false, default
652 arguments are a compile-time error.
653
654 Default: 1
655
656 "install_sub"
657 (sub name or reference) If this is set, named functions declared
658 with this keyword are not entered into the symbol table directly.
659 Instead the subroutine specified here (by name or reference) is
660 called with two arguments, the name of the function being declared
661 and a reference to its body.
662
663 Default: nothing
664
665 "invocant"
666 (boolean) Whether functions declared with this keyword should allow
667 explicitly specifying invocant(s) at the beginning of the parameter
668 list (as in "($invocant: ...)" or "($invocant1, $invocant2,
669 $invocant3: ...)").
670
671 Default: 0
672
673 "name"
674 (string) There are three possible values for this option.
675 'required' means functions declared with this keyword must have a
676 name. 'prohibited' means specifying a name is not allowed.
677 'optional' means this keyword can be used for both named and
678 anonymous functions.
679
680 Default: 'optional'
681
682 "named_parameters"
683 (boolean) Whether functions declared with this keyword should allow
684 named parameters. If false, named parameters are a compile-time
685 error.
686
687 Default: 1
688
689 "reify_type"
690 (coderef or 'auto' or 'moose') The code reference used to resolve
691 type constraints in functions declared with this keyword. It is
692 called once for each type constraint that doesn't use the "( EXPR
693 )" syntax, with one argument, the text of the type in the parameter
694 list (e.g. 'ArrayRef[Int]'). The package the function declaration
695 is in is available through "caller".
696
697 The only requirement is that the returned value (here referred to
698 as $tc, for "type constraint") is an object that provides
699 "$tc->check($value)" and "$tc->get_message($value)" methods.
700 "check" is called to determine whether a particular value is valid;
701 it should return a true or false value. "get_message" is called on
702 values that fail the "check" test; it should return a string that
703 describes the error.
704
705 Type constraints can optionally support two additional features:
706
707 • Coercion. If the "$tc->has_coercion" method exists and returns
708 a true value, every incoming argument is automatically
709 transformed by "$value = $tc->coerce($value)" before being
710 type-checked.
711
712 • Inlining. If the "$tc->can_be_inlined" method exists and
713 returns a true value, the call to "$tc->check($value)" is
714 automatically replaced by the code returned (in string form)
715 from "$tc->inline_check('$value')". (For compatibility with
716 Moose, if $tc has no "inline_check" method,
717 "$tc->_inline_check('$value')" is used instead.)
718
719 Instead of a code reference you can also specify one of two
720 strings.
721
722 'auto' stands for a built-in type reifier that treats identifiers
723 as subroutine names, "[" "]" as an array reference, "~" as bitwise
724 complement, "/" as division, "&" as bitwise and, and "|" as bitwise
725 or. In other words, it parses and executes type constraints
726 (mostly) as if they had been Perl source code.
727
728 'moose' stands for a built-in type reifier that loads
729 Moose::Util::TypeConstraints and just forwards to
730 "find_or_create_isa_type_constraint".
731
732 Default: 'auto'
733
734 "runtime"
735 (boolean) Whether functions declared with this keyword should be
736 installed into the symbol table at runtime. If false, named
737 functions are defined (or their "install_sub" is invoked if
738 specified) immediately after their declaration is parsed (as with
739 "sub"). If true, function declarations become normal statements
740 that only take effect at runtime (similar to "*foo = sub { ... };"
741 or "$install_sub->('foo', sub { ... });", respectively).
742
743 Default: 0
744
745 "shift"
746 (string or arrayref) In its simplest form, this is the name of a
747 variable that acts as the default invocant (a required leading
748 argument that is removed from @_) for all functions declared with
749 this keyword (e.g. '$self' for methods). You can also set this to
750 an array reference of strings, which lets you specify multiple
751 default invocants, or even to an array reference of array
752 references of the form "[ $name, $type ]" (where $name is the
753 variable name and $type is a type constraint object), which lets
754 you specify multiple default invocants with type constraints.
755
756 If you define any default invocants here and also allow individual
757 declarations to override the default (with "invocant => 1"), the
758 number of overridden invocants must match the default. For example,
759 "method" has a default invocant of $self, so "method foo($x, $y:
760 $z)" is invalid because it tries to define two invocants.
761
762 Default: "[]" (meaning no invocants)
763
764 "strict"
765 (boolean) Whether functions declared with this keyword should do
766 "strict" checks on their arguments. Currently setting this simply
767 sets "check_argument_count" to the same value with no other
768 effects.
769
770 Default: nothing
771
772 "types"
773 (boolean) Whether functions declared with this keyword should allow
774 type constraints in their parameter lists. If false, trying to use
775 type constraints is a compile-time error.
776
777 Default: 1
778
779 You can get the same effect as "use Function::Parameters;" by saying:
780
781 use Function::Parameters {
782 fun => {
783 # 'fun' uses default settings only
784 },
785 method => {
786 attributes => ':method',
787 shift => '$self',
788 invocant => 1,
789 # the rest is defaults
790 },
791 };
792
793 Configuration bundles
794
795 Because specifying all these configuration options from scratch each
796 time is a lot of writing, "Function::Parameters" offers configuration
797 bundles in the form of special strings. These strings can be used to
798 replace a configuration hash completely or as the value of the
799 "defaults" pseudo-option within a configuration hash. The latter lets
800 you use the configuration bundle behind the string to provide defaults
801 and tweak them with your own settings.
802
803 The following bundles are available:
804
805 "function_strict"
806 Equivalent to "{}", i.e. all defaults.
807
808 "function_lax"
809 Equivalent to:
810
811 {
812 defaults => 'function_strict',
813 strict => 0,
814 }
815
816 i.e. just like "function_strict" but with "strict" checks turned
817 off.
818
819 "function"
820 Equivalent to "function_strict". This is what the default "fun"
821 keyword actually uses. (In version 1 of this module, "function" was
822 equivalent to "function_lax".)
823
824 "method_strict"
825 Equivalent to:
826
827 {
828 defaults => 'function_strict',
829 attributes => ':method',
830 shift => '$self',
831 invocant => 1,
832 }
833
834 "method_lax"
835 Equivalent to:
836
837 {
838 defaults => 'method_strict',
839 strict => 0,
840 }
841
842 i.e. just like "method_strict" but with "strict" checks turned off.
843
844 "method"
845 Equivalent to "method_strict". This is what the default "method"
846 keyword actually uses. (In version 1 of this module, "method" was
847 equivalent to "method_lax".)
848
849 "classmethod_strict"
850 Equivalent to:
851
852 {
853 defaults => 'method_strict',
854 shift => '$class',
855 }
856
857 i.e. just like "method_strict" but the implicit first parameter is
858 called $class, not $self.
859
860 "classmethod_lax"
861 Equivalent to:
862
863 {
864 defaults => 'classmethod_strict',
865 strict => 0,
866 }
867
868 i.e. just like "classmethod_strict" but with "strict" checks turned
869 off.
870
871 "classmethod"
872 Equivalent to "classmethod_strict". This is currently not used
873 anywhere within "Function::Parameters".
874
875 "around"
876 Equivalent to:
877
878 {
879 defaults => 'method',
880 install_sub => 'around',
881 shift => ['$orig', '$self'],
882 runtime => 1,
883 name => 'required',
884 }
885
886 i.e. just like "method" but with a custom installer ('around'), two
887 implicit first parameters, only taking effect at runtime, and a
888 method name is required.
889
890 "before"
891 Equivalent to:
892
893 {
894 defaults => 'method',
895 install_sub => 'before',
896 runtime => 1,
897 name => 'required',
898 }
899
900 i.e. just like "method" but with a custom installer ('before'),
901 only taking effect at runtime, and a method name is required.
902
903 "after"
904 Equivalent to:
905
906 {
907 defaults => 'method',
908 install_sub => 'after',
909 runtime => 1,
910 name => 'required',
911 }
912
913 i.e. just like "method" but with a custom installer ('after'), only
914 taking effect at runtime, and a method name is required.
915
916 "augment"
917 Equivalent to:
918
919 {
920 defaults => 'method',
921 install_sub => 'augment',
922 runtime => 1,
923 name => 'required',
924 }
925
926 i.e. just like "method" but with a custom installer ('augment'),
927 only taking effect at runtime, and a method name is required.
928
929 "override"
930 Equivalent to:
931
932 {
933 defaults => 'method',
934 install_sub => 'override',
935 runtime => 1,
936 name => 'required',
937 }
938
939 i.e. just like "method" but with a custom installer ('override'),
940 only taking effect at runtime, and a method name is required.
941
942 You can get the same effect as "use Function::Parameters;" by saying:
943
944 use Function::Parameters {
945 fun => { defaults => 'function' },
946 method => { defaults => 'method' },
947 };
948
949 or:
950
951 use Function::Parameters {
952 fun => 'function',
953 method => 'method',
954 };
955
956 Import tags
957
958 In addition to hash references you can also use special strings in your
959 import list. The following import tags are available:
960
961 'fun'
962 Equivalent to "{ fun => 'function' }".
963
964 'method'
965 Equivalent to "{ method => 'method' }".
966
967 'classmethod'
968 Equivalent to "{ classmethod => 'classmethod' }".
969
970 'before'
971 Equivalent to "{ before => 'before' }".
972
973 'after'
974 Equivalent to "{ after => 'after' }".
975
976 'around'
977 Equivalent to "{ around => 'around' }".
978
979 'augment'
980 Equivalent to "{ augment => 'augment' }".
981
982 'override'
983 Equivalent to "{ override => 'override' }".
984
985 ':strict'
986 Equivalent to "{ fun => 'function_strict', method =>
987 'method_strict' }" but that's just the default behavior anyway.
988
989 ':lax'
990 Equivalent to "{ fun => 'function_lax', method => 'method_lax' }",
991 i.e. it provides "fun" and "method" keywords that define functions
992 that don't check their arguments.
993
994 ':std'
995 Equivalent to 'fun', 'method'. This is what's used by default:
996
997 use Function::Parameters;
998
999 is the same as:
1000
1001 use Function::Parameters qw(:std);
1002
1003 ':modifiers'
1004 Equivalent to 'before', 'after', 'around', 'augment', 'override'.
1005
1006 For example, when you say
1007
1008 use Function::Parameters qw(:modifiers);
1009
1010 ":modifiers" is an import tag that expands to
1011
1012 use Function::Parameters qw(before after around augment override);
1013
1014 Each of those is another import tag. Stepping through the first one:
1015
1016 use Function::Parameters qw(before);
1017
1018 is equivalent to:
1019
1020 use Function::Parameters { before => 'before' };
1021
1022 This says to define the keyword "before" according to the configuration
1023 bundle "before":
1024
1025 use Function::Parameters {
1026 before => {
1027 defaults => 'method',
1028 install_sub => 'before',
1029 runtime => 1,
1030 name => 'required',
1031 },
1032 };
1033
1034 The "defaults => 'method'" part pulls in the contents of the 'method'
1035 configuration bundle (which is the same as 'method_strict'):
1036
1037 use Function::Parameters {
1038 before => {
1039 defaults => 'function_strict',
1040 attributes => ':method',
1041 shift => '$self',
1042 invocant => 1,
1043 install_sub => 'before',
1044 runtime => 1,
1045 name => 'required',
1046 },
1047 };
1048
1049 This in turn uses the 'function_strict' configuration bundle (which is
1050 empty because it consists of default values only):
1051
1052 use Function::Parameters {
1053 before => {
1054 attributes => ':method',
1055 shift => '$self',
1056 invocant => 1,
1057 install_sub => 'before',
1058 runtime => 1,
1059 name => 'required',
1060 },
1061 };
1062
1063 But if we wanted to be completely explicit, we could write this as:
1064
1065 use Function::Parameters {
1066 before => {
1067 check_argument_count => 1,
1068 check_argument_types => 1,
1069 default_arguments => 1,
1070 named_parameters => 1,
1071 reify_type => 'auto',
1072 types => 1,
1073
1074 attributes => ':method',
1075 shift => '$self',
1076 invocant => 1,
1077 install_sub => 'before',
1078 runtime => 1,
1079 name => 'required',
1080 },
1081 };
1082
1083 Incompatibilites with version 1 of "Function::Parameters"
1084 • Version 1 defaults to lax mode (no argument checks). To get the
1085 same behavior on both version 1 and version 2, explicitly write
1086 either "use Function::Parameters qw(:strict);" (the new default) or
1087 "use Function::Parameters qw(:lax);" (the old default). (Or write
1088 "use Function::Parameters 2;" to trigger an error if an older
1089 version of "Function::Parameters" is loaded.)
1090
1091 • Parameter lists used to be optional. The syntax "fun foo { ... }"
1092 would accept any number of arguments. This syntax has been removed;
1093 you now have to write "fun foo(@) { ... }" to accept (and ignore)
1094 all arguments. On the other hand, if you meant for the function to
1095 take no arguments, write "fun foo() { ... }".
1096
1097 • There used to be a shorthand syntax for prototypes: Using :(...)
1098 (i.e. an attribute with an empty name) as the first attribute was
1099 equivalent to :prototype(...). This syntax has been removed.
1100
1101 • The default type reifier used to be hardcoded to use Moose (as in
1102 "reify_type => 'moose'"). This has been changed to use whatever
1103 type functions are in scope ("reify_type => 'auto'").
1104
1105 • Type reifiers used to see the wrong package in "caller". As a
1106 workaround the correct calling package used to be passed as a
1107 second argument. This problem has been fixed and the second
1108 argument has been removed. (Technically this is a core perl bug (GH
1109 #15597 <https://github.com/Perl/perl5/issues/15597>) that wasn't so
1110 much fixed as worked around in "Function::Parameters".)
1111
1112 If you want your type reifier to be compatible with both versions,
1113 you can do this:
1114
1115 sub my_reifier {
1116 my ($type, $package) = @_;
1117 $package //= caller;
1118 ...
1119 }
1120
1121 Or using "Function::Parameters" itself:
1122
1123 fun my_reifier($type, $package = caller) {
1124 ...
1125 }
1126
1128 Function::Parameters: $^H{'Function::Parameters/config'} is not a
1129 reference; skipping: HASH(%s)
1130 Function::Parameters relies on being able to put references in
1131 "%^H" (the lexical compilation context) and pull them out again at
1132 compile time. You may see the warning above if what used to be a
1133 reference got turned into a plain string. In this case,
1134 Function::Parameters gives up and automatically disables itself, as
1135 if by "no Function::Parameters;".
1136
1137 You can disable the warning in a given scope by saying "no warnings
1138 'Function::Parameters'"; see warnings.
1139
1140 Currently the only case I'm aware of where this happens with core
1141 perl is embedded code blocks in regexes that are compiled at
1142 runtime (in a scope where "use re 'eval'" is active):
1143
1144 use strict;
1145 use warnings;
1146 use Function::Parameters;
1147 use re 'eval';
1148
1149 my $code = '(?{ print "embedded code\n"; })';
1150 my $regex = qr/$code/;
1151
1152 In my opinion, this is a bug in perl: GH #20950
1153 <https://github.com/Perl/perl5/issues/20950>.
1154
1155 This case used to be a hard error in versions 2.001005 and before
1156 of this module.
1157
1159 After installing, you can find documentation for this module with the
1160 "perldoc" command.
1161
1162 perldoc Function::Parameters
1163
1164 You can also look for information at
1165 <https://metacpan.org/pod/Function::Parameters>.
1166
1167 To see a list of open bugs, visit
1168 <https://rt.cpan.org/Public/Dist/Display.html?Name=Function-Parameters>.
1169
1170 To report a new bug, send an email to "bug-Function-Parameters [at]
1171 rt.cpan.org".
1172
1174 Function::Parameters::Info, Moose, Moo, Type::Tiny
1175
1177 Lukas Mai, "<l.mai at web.de>"
1178
1180 Copyright (C) 2010-2014, 2017, 2023 Lukas Mai.
1181
1182 This program is free software; you can redistribute it and/or modify it
1183 under the terms of either: the GNU General Public License as published
1184 by the Free Software Foundation; or the Artistic License.
1185
1186 See <https://dev.perl.org/licenses/> for more information.
1187
1188
1189
1190perl v5.38.0 2023-07-20 Function::Parameters(3)