-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathParameters.pm
1657 lines (1251 loc) · 45.5 KB
/
Parameters.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package Function::Parameters;
use v5.14.0;
use warnings;
use Carp qw(croak confess);
use Scalar::Util qw(blessed);
sub _croak {
my (undef, $file, $line) = caller 1;
push @_, " at $file line $line.\n" unless $_[-1] =~ /\n\z/;
die @_;
}
use XSLoader;
BEGIN {
our $VERSION = '2.001001';
#$VERSION =~ s/-TRIAL[0-9]*\z//;
XSLoader::load;
}
sub _assert_valid_identifier {
my ($name, $with_dollar) = @_;
my $bonus = $with_dollar ? '\$' : '';
$name =~ /\A${bonus}[^\W\d]\w*\z/
or confess qq{"$name" doesn't look like a valid identifier};
}
sub _assert_valid_attributes {
my ($attrs) = @_;
$attrs =~ m{
\A \s*+
: \s*+
(?&ident) (?! [^\s:(] ) (?¶m)?+ \s*+
(?:
(?: : \s*+ )?
(?&ident) (?! [^\s:(] ) (?¶m)?+ \s*+
)*+
\z
(?(DEFINE)
(?<ident>
[^\W\d]
\w*+
)
(?<param>
\(
[^()\\]*+
(?:
(?:
\\ .
|
(?¶m)
)
[^()\\]*+
)*+
\)
)
)
}sx or confess qq{"$attrs" doesn't look like valid attributes};
}
sub _reify_type_moose {
require Moose::Util::TypeConstraints;
Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($_[0])
}
sub _malformed_type {
my ($type, $msg) = @_;
my $pos = pos $_[0];
substr $type, $pos, 0, ' <-- HERE ';
croak "Malformed type: $msg marked by <-- HERE in '$type'";
}
sub _reify_type_auto_term {
# (str, caller)
$_[0] =~ /\G ( \w+ (?: :: \w+)* ) \s* /xgc or _malformed_type $_[0], "missing type name";
my $name = $1;
$name = "$_[1]::$name" unless $name =~ /::/;
my $fun = do {
no strict 'refs';
defined &$name or croak "Undefined type name $name";
\&$name
};
$_[0] =~ /\G \[ \s* /xgc
or return $fun;
my @args;
until ($_[0] =~ /\G \] \s* /xgc) {
$_[0] =~ /\G , \s* /xgc or _malformed_type $_[0], "missing ',' or ']'"
if @args;
push @args, &_reify_type_auto_union;
}
sub { $fun->([map $_->(), @args]) }
}
sub _reify_type_auto_union {
# (str, caller)
my $fun = &_reify_type_auto_term;
while ($_[0] =~ /\G \| \s* /xgc) {
my $right = &_reify_type_auto_term;
my $left = $fun;
$fun = sub { $left->() | $right->() };
}
$fun
}
sub _reify_type_auto {
my ($type) = @_;
my $caller = caller;
$type =~ /\G \s+ /xgc;
my $tfun = _reify_type_auto_union $type, $caller;
$type =~ /\G \z/xgc or _malformed_type $type, "trailing garbage";
$tfun->()
}
sub _delete_default {
my ($href, $key, $default) = @_;
exists $href->{$key} ? delete $href->{$key} : $default
}
sub _find_or_add_idx {
my ($array, $x) = @_;
my $index;
for my $i (0 .. $#$array) {
if ($array->[$i] == $x) {
$index = $i;
last;
}
}
unless (defined $index) {
$index = @$array;
push @$array, $x;
}
$index
}
my %type_map = (
function_strict => {},
function_lax => {
defaults => 'function_strict',
strict => 0,
},
function => { defaults => 'function_strict' },
method_strict => {
defaults => 'function_strict',
attributes => ':method',
shift => '$self',
invocant => 1,
},
method_lax => {
defaults => 'method_strict',
strict => 0,
},
method => { defaults => 'method_strict' },
classmethod_strict => {
defaults => 'method_strict',
shift => '$class',
},
classmethod_lax => {
defaults => 'classmethod_strict',
strict => 0,
},
classmethod => { defaults => 'classmethod_strict' },
around => {
defaults => 'method',
name => 'required',
install_sub => 'around',
shift => ['$orig', '$self'],
runtime => 1,
},
(
map +(
$_ => {
defaults => 'method',
name => 'required',
install_sub => $_,
runtime => 1,
}
), qw(
before after augment override
),
),
);
my %import_map = (
fun => 'function',
(
map +($_ => $_),
qw(
method
classmethod
before
after
around
augment
override
)
),
':strict' => {
fun => 'function_strict',
method => 'method_strict',
},
':lax' => {
fun => 'function_lax',
method => 'method_lax',
},
':std' => [qw(fun method)],
':modifiers' => [qw(
before
after
around
augment
override
)],
);
for my $v (values %import_map) {
if (ref $v eq 'ARRAY') {
$v = {
map +($_ => $import_map{$_} || die "Internal error: $v => $_"),
@$v
};
}
}
sub import {
my $class = shift;
my %imports;
@_ = qw(:std) if !@_;
for my $item (@_) {
my $part;
if (ref $item) {
$part = $item;
} else {
my $type = $import_map{$item}
or croak qq{"$item" is not exported by the $class module};
$part = ref $type
? $type
: { $item => $type };
}
@imports{keys %$part} = values %$part;
}
my %spec;
for my $name (sort keys %imports) {
_assert_valid_identifier $name;
my $proto_type = $imports{$name};
$proto_type = {defaults => $proto_type} unless ref $proto_type;
my %type = %$proto_type;
while (my $defaults = delete $type{defaults}) {
my $base = $type_map{$defaults}
or confess qq["$defaults" doesn't look like a valid type (one of ${\join ', ', sort keys %type_map})];
%type = (%$base, %type);
}
if (exists $type{strict}) {
$type{check_argument_count} ||= $type{strict};
delete $type{strict};
}
my %clean;
$clean{name} = delete $type{name} // 'optional';
$clean{name} =~ /\A(?:optional|required|prohibited)\z/
or confess qq["$clean{name}" doesn't look like a valid name attribute (one of optional, required, prohibited)];
$clean{attrs} = delete $type{attributes} // '';
_assert_valid_attributes $clean{attrs} if $clean{attrs};
if (!exists $type{reify_type}) {
$clean{reify_type} = \&_reify_type_auto;
} else {
my $rt = delete $type{reify_type} // '(undef)';
if (!ref $rt) {
$rt =
$rt eq 'auto' ? \&_reify_type_auto :
$rt eq 'moose' ? \&_reify_type_moose :
confess qq{"$rt" isn't a known predefined type reifier};
} elsif (ref $rt ne 'CODE') {
confess qq{"$rt" doesn't look like a type reifier};
}
$clean{reify_type} = $rt;
}
if (!exists $type{install_sub}) {
$clean{install_sub} = '';
} else {
my $is = delete $type{install_sub};
if (!ref $is) {
_assert_valid_identifier $is;
} elsif (ref $is ne 'CODE') {
confess qq{"$is" doesn't look like a sub installer};
}
$clean{install_sub} = $is;
}
$clean{shift} = do {
my $shift = delete $type{shift} // [];
$shift = [$shift] if !ref $shift;
my $str = '';
my @shifty_types;
for my $item (@$shift) {
my ($name, $type);
if (ref $item) {
@$item == 2 or confess "A 'shift' item must have 2 elements, not " . @$item;
($name, $type) = @$item;
} else {
$name = $item;
}
_assert_valid_identifier $name, 1;
$name eq '$_' and confess q[Using "$_" as a parameter is not supported];
$str .= $name;
if (defined $type) {
blessed($type) or confess "${name}'s type must be an object, not $type";
my $index = _find_or_add_idx \@shifty_types, $type;
$str .= "/$index";
}
$str .= ' ';
}
$clean{shift_types} = \@shifty_types;
$str
};
$clean{default_arguments} = _delete_default \%type, 'default_arguments', 1;
$clean{named_parameters} = _delete_default \%type, 'named_parameters', 1;
$clean{types} = _delete_default \%type, 'types', 1;
$clean{invocant} = _delete_default \%type, 'invocant', 0;
$clean{runtime} = _delete_default \%type, 'runtime', 0;
$clean{check_argument_count} = _delete_default \%type, 'check_argument_count', 1;
$clean{check_argument_types} = _delete_default \%type, 'check_argument_types', 1;
%type and confess "Invalid keyword property: @{[sort keys %type]}";
$spec{$name} = \%clean;
}
my %config = %{$^H{+HINTK_CONFIG} // {}};
for my $kw (keys %spec) {
my $type = $spec{$kw};
my $flags =
$type->{name} eq 'prohibited' ? FLAG_ANON_OK :
$type->{name} eq 'required' ? FLAG_NAME_OK :
FLAG_ANON_OK | FLAG_NAME_OK
;
$flags |= FLAG_DEFAULT_ARGS if $type->{default_arguments};
$flags |= FLAG_CHECK_NARGS if $type->{check_argument_count};
$flags |= FLAG_CHECK_TARGS if $type->{check_argument_types};
$flags |= FLAG_INVOCANT if $type->{invocant};
$flags |= FLAG_NAMED_PARAMS if $type->{named_parameters};
$flags |= FLAG_TYPES_OK if $type->{types};
$flags |= FLAG_RUNTIME if $type->{runtime};
$config{$kw} = {
HINTSK_FLAGS, => $flags,
HINTSK_SHIFT, => $type->{shift},
HINTSK_ATTRS, => $type->{attrs},
HINTSK_REIFY, => $type->{reify_type},
HINTSK_INSTL, => $type->{install_sub},
!@{$type->{shift_types}} ? () : (
HINTSK_SHIF2, => $type->{shift_types},
),
};
}
$^H{+HINTK_CONFIG} = \%config;
}
sub unimport {
my $class = shift;
if (!@_) {
delete $^H{+HINTK_CONFIG};
return;
}
my %config = %{$^H{+HINTK_CONFIG}};
delete @config{@_};
$^H{+HINTK_CONFIG} = \%config;
}
our %metadata;
sub _register_info {
my (
$key,
$declarator,
$shift,
$positional_required,
$positional_optional,
$named_required,
$named_optional,
$slurpy,
$slurpy_type,
) = @_;
my $info = {
declarator => $declarator,
shift => $shift,
positional_required => $positional_required,
positional_optional => $positional_optional,
named_required => $named_required,
named_optional => $named_optional,
slurpy => defined $slurpy ? [$slurpy, $slurpy_type] : undef,
};
$metadata{$key} = $info;
}
sub _mkparam1 {
my ($pair) = @_;
my ($v, $t) = @{$pair || []} or return undef;
Function::Parameters::Param->new(
name => $v,
type => $t,
)
}
sub _mkparams {
my @r;
while (my ($v, $t) = splice @_, 0, 2) {
push @r, Function::Parameters::Param->new(
name => $v,
type => $t,
);
}
\@r
}
sub info {
my ($func) = @_;
my $key = _cv_root $func or return undef;
my $info = $metadata{$key} or return undef;
require Function::Parameters::Info;
Function::Parameters::Info->new(
keyword => $info->{declarator},
nshift => $info->{shift},
slurpy => _mkparam1($info->{slurpy}),
(
map +("_$_" => _mkparams @{$info->{$_}}),
qw(
positional_required
positional_optional
named_required
named_optional
)
)
)
}
'ok'
__END__
=encoding UTF-8
=for highlighter language=perl
=head1 NAME
Function::Parameters - define functions and methods with parameter lists ("subroutine signatures")
=head1 SYNOPSIS
use Function::Parameters;
# plain function
fun foo($x, $y, $z = 5) {
return $x + $y + $z;
}
print foo(1, 2), "\n"; # 8
# method with implicit $self
method bar($label, $n) {
return "$label: " . ($n * $self->scale);
}
# named arguments: order doesn't matter in the call
fun create_point(:$x, :$y, :$color) {
print "creating a $color point at ($x, $y)\n";
}
create_point(
color => "red",
x => 10,
y => 5,
);
package Derived {
use Function::Parameters qw(:std :modifiers);
use Moo;
extends 'Base';
has 'go_big' => (
is => 'ro',
);
# "around" method with implicit $orig and $self
around size() {
return $self->$orig() * 2 if $self->go_big;
return $self->$orig();
}
}
=head1 DESCRIPTION
This module provides two new keywords, C<fun> and C<method>, for defining
functions and methods with parameter lists. At minimum this saves you from
having to unpack C<@_> manually, but this module can do much more for you.
The parameter lists provided by this module are similar to the C<signatures>
feature available in perl v5.20+. However, this module supports all perl
versions starting from v5.14, it offers far more features than core signatures,
and it is not experimental. The downside is that you need a C compiler if you
want to install it from source, as it uses Perl's
L<keyword plugin|perlapi/PL_keyword_plugin> API in order to work reliably
without requiring a source filter.
=head2 Default functionality
This module is a lexically scoped pragma: If you C<use Function::Parameters>
inside a block or file, the keywords won't be available outside of that block
or file.
You can also disable C<Function::Parameters> within a block:
{
no Function::Parameters; # disable all keywords
...
}
Or explicitly list the keywords you want to disable:
{
no Function::Parameters qw(method);
# 'method' is a normal identifier here
...
}
You can also explicitly list the keywords you want to enable:
use Function::Parameters qw(fun); # provides 'fun' but not 'method'
use Function::Parameters qw(method); # provides 'method' but not 'fun'
=head3 Simple parameter lists
By default you get two keywords, C<fun> and C<method> (but see
L</Customizing and extending> below). C<fun> is very similar to C<sub>. You can
use it to define both named and anonymous functions:
fun left_pad($str, $n) {
return sprintf '%*s', $n, $str;
}
print left_pad("hello", 10), "\n";
my $twice = fun ($x) { $x * 2 };
print $twice->(21), "\n";
In the simplest case the parameter list is just a comma-separated list of zero
or more scalar variables (enclosed in parentheses, following the function name,
if any).
C<Function::Parameters> automatically validates the arguments your function is
called with. If the number of arguments doesn't match the parameter list, an
exception is thrown.
Apart from that, the parameter variables are defined and initialized as if by:
sub left_pad {
sub left_pad;
my ($str, $n) = @_;
...
}
In particular, C<@_> is still available in functions defined by C<fun> and
holds the original argument list.
The inner C<sub left_pad;> declaration is intended to illustrate that the name
of the function being defined is in scope in its own body, meaning you can call
it recursively without having to use parentheses:
fun fac($n) {
return 1 if $n < 2;
return $n * fac $n - 1;
}
In a normal C<sub> the last line would have had to be written
C<return $n * fac($n - 1);>.
C<method> is almost the same as C<fun> but automatically creates a C<$self>
variable as the first parameter (which is removed from C<@_>):
method foo($x, $y) {
...
}
# works like:
sub foo :method {
my $self = shift;
my ($x, $y) = @_;
...
}
As you can see, the C<:method> attribute is also added automatically (see
L<attributes/method> for details).
In some cases (e.g. class methods) C<$self> is not the best name for the
invocant of the method. You can override it on a case-by-case basis by putting
a variable name followed by a C<:> (colon) as the first thing in the parameter
list:
method new($class: $x, $y) {
return bless { x => $x, y => $y }, $class;
}
Here the invocant is named C<$class>, not C<$self>. It looks a bit weird but
still works the same way if the remaining parameter list is empty:
method from_env($class:) {
return $class->new($ENV{x}, $ENV{y});
}
=head3 Default arguments
(Most of the following examples use C<fun> only. Unless specified otherwise
everything applies to C<method> as well.)
You can make some arguments optional by giving them default values.
fun passthrough($x, $y = 42, $z = []) {
return ($x, $y, $z);
}
In this example the first parameter C<$x> is required but C<$y> and C<$z> are
optional.
passthrough('a', 'b', 'c', 'd') # error: Too many arguments
passthrough('a', 'b', 'c') # returns ('a', 'b', 'c')
passthrough('a', 'b') # returns ('a', 'b', [])
passthrough('a', undef) # returns ('a', undef, [])
passthrough('a') # returns ('a', 42, [])
passthrough() # error: Too few arguments
Default arguments are evaluated whenever a corresponding real argument is not
passed in by the caller. C<undef> counts as a real argument; you can't use the
default value for parameter I<N> and still pass a value for parameter I<N+1>.
C<$z = []> means each call that doesn't pass a third argument gets a new array
reference (they're not shared between calls).
Default arguments are evaluated as part of the function body, allowing for
silliness such as:
fun weird($name = return "nope") {
print "Hello, $name!\n";
return $name;
}
weird("Larry"); # prints "Hello, Larry!" and returns "Larry"
weird(); # returns "nope" immediately; function body doesn't run
Preceding parameters are in scope for default arguments:
fun dynamic_default($x, $y = length $x) {
return "$x/$y";
}
dynamic_default("hello", 0) # returns "hello/0"
dynamic_default("hello") # returns "hello/5"
dynamic_default("abc") # returns "abc/3"
If you just want to make a parameter optional without giving it a special
value, write C<$param = undef>. There is a special shortcut syntax for
this case: C<$param = undef> can also be written C<$param => (with no following
expression).
fun foo($x = undef, $y = undef, $z = undef) {
# three arguments, all optional
...
}
fun foo($x=, $y=, $z=) {
# shorter syntax, same meaning
...
}
Optional parameters must come at the end. It is not possible to have a required
parameter after an optional one.
=head3 Slurpy/rest parameters
The last parameter of a function or method can be an array. This lets you slurp
up any number of arguments the caller passes (0 or more).
fun scale($factor, @values) {
return map { $_ * $factor } @values;
}
scale(10, 1 .. 4) # returns (10, 20, 30, 40)
scale(10) # returns ()
You can also use a hash, but then the number of arguments has to be even.
=head3 Named parameters
As soon as your functions take more than three arguments, it gets harder to
keep track of what argument means what:
foo($handle, $w, $h * 2 + 15, 1, 24, 'icon');
# what do these arguments mean?
C<Function::Parameters> offers an alternative for these kinds of situations in
the form of named parameters. Unlike the parameters described previously, which
are identified by position, these parameters are identified by name:
fun create_point(:$x, :$y, :$color) {
...
}
# Case 1
create_point(
x => 50,
y => 50,
color => 0xff_00_00,
);
To create a named parameter, put a C<:> (colon) in front of it in the parameter
list. When the function is called, the arguments have to be supplied in the
form of a hash initializer (a list of alternating keys/values). As with a hash,
the order of key/value pairs doesn't matter (except in the case of duplicate
keys, where the last occurrence wins):
# Case 2
create_point(
color => 0xff_00_00,
x => 50,
y => 50,
);
# Case 3
create_point(
x => 200,
color => 0x12_34_56,
color => 0xff_00_00,
x => 50,
y => 50,
);
Case 1, Case 2, and Case 3 all mean the same thing.
As with positional parameters, you can make named parameters optional by
supplying a L<default argument|/Default arguments>:
fun create_point(:$x, :$y, :$color = 0x00_00_00) {
...
}
create_point(x => 0, y => 64) # color => 0x00_00_00 is implicit
If you want to accept any key/value pairs, you can add a
L<rest parameter|/Slurpy/rest parameters> (hashes are particularly useful):
fun accept_all_keys(:$name, :$age, %rest) {
...
}
accept_all_keys(
age => 42,
gender => 2,
name => "Jamie",
marbles => [],
);
# $name = "Jamie";
# $age = 42;
# %rest = (
# gender => 2,
# marbles => [],
# );
You can combine positional and named parameters but all positional parameters
have to come first:
method output(
$data,
:$handle = $self->output_handle,
:$separator = $self->separator,
:$quote_fields = 0,
) {
...
}
$obj->output(["greetings", "from", "space"]);
$obj->output(
["a", "random", "example"],
quote_fields => 1,
separator => ";",
);
=head3 Unnamed parameters
If your function doesn't use a particular parameter at all, you can omit its
name and just write a sigil in the parameter list:
register_callback('click', fun ($target, $) {
...
});
Here we're calling a hypothetical C<register_callback> function that registers
our coderef to be called in response to a C<click> event. It will pass two
arguments to the click handler, but the coderef only cares about the first one
(C<$target>). The second parameter doesn't even get a name (just a sigil,
C<$>). This marks it as unused.
This case typically occurs when your functions have to conform to an externally
imposed interface, e.g. because they're called by someone else. It can happen
with callbacks or methods that don't need all of the arguments they get.
You can use unnamed L<slurpy parameters|/Slurpy/rest parameters> to accept and
ignore all following arguments. In particular, C<fun foo(@)> is a lot like
C<sub foo> in that it accepts and ignores any number of arguments (apart from
leaving them in C<@_>).
=head3 Type constraints
It is possible to automatically check the types of arguments passed to your
function. There are two ways to do this.
=over
=item 1.
use Types::Standard qw(Str Int ArrayRef);
fun foo(Str $label, ArrayRef[Int] $counts) {
...
}
In this variant you simply put the name of a type in front of a parameter. The
way this works is that C<Function::Parameters> parses the type using very
simple rules:
=over
=item *
A I<type> is a sequence of one or more simple types, separated by C<|> (pipe).
C<|> is meant for union types (e.g. C<Str | ArrayRef[Int]> would accept either
a string or reference to an array of integers).
=item *
A I<simple type> is an identifier, optionally followed by a list of one or more
types, separated by C<,> (comma), enclosed in C<[> C<]> (square brackets).
=back
C<Function::Parameters> then resolves simple types by looking for functions of
the same name in your current package. A type specification like
C<Str | ArrayRef[Int]> ends up running the Perl code
C<Str() | ArrayRef([Int()])> (at compile time, while the function definition is
being processed). In other words, C<Function::Parameters> doesn't support any
types natively; it simply uses whatever is in scope.
You don't have to define these functions yourself. You can also import them
from a type library such as L<C<Types::Standard>|Types::Standard> or
L<C<MooseX::Types::Moose>|MooseX::Types::Moose>.
The only requirement is that the returned value (here referred to as C<$tc>,
for "type constraint") is an object that provides C<< $tc->check($value) >>
and C<< $tc->get_message($value) >> methods. C<check> is called to determine
whether a particular value is valid; it should return a true or false value.
C<get_message> is called on values that fail the C<check> test; it should
return a string that describes the error.
=item 2.
my ($my_type, $some_other_type);
BEGIN {
$my_type = Some::Constraint::Class->new;
$some_other_type = Some::Other::Class->new;
}
fun foo(($my_type) $label, ($some_other_type) $counts) {
...
}
In this variant you enclose an arbitrary Perl expression in C<(> C<)>
(parentheses) and put it in front of a parameter. This expression is evaluated
at compile time and must return a type constraint object as described above.
(If you use variables here, make sure they're defined at compile time.)
=back
=head3 Method modifiers
C<Function::Parameters> has support for method modifiers as provided by
L<C<Moo>|Moo> or L<C<Moose>|Moose>. They're not exported by default, so you
have to say
use Function::Parameters qw(:modifiers);
to get them. This line gives you method modifiers I<only>; C<fun> and C<method>
are not defined. To get both the standard keywords and method modifiers, you
can either write two C<use> lines:
use Function::Parameters;
use Function::Parameters qw(:modifiers);
or explicitly list the keywords you want:
use Function::Parameters qw(fun method :modifiers);
or add the C<:std> import tag (which gives you the default import behavior):
use Function::Parameters qw(:std :modifiers);
This defines the following additional keywords: C<before>, C<after>, C<around>,
C<augment>, C<override>. These work mostly like C<method>, but they don't
install the function into your package themselves. Instead they invoke whatever
C<before>, C<after>, C<around>, C<augment>, or C<override> function
(respectively) is in scope to do the job.
before foo($x, $y, $z) {
...
}
works like
&before('foo', method ($x, $y, $z) {
...
});
C<after>, C<augment>, and C<override> work the same way.
C<around> is slightly different: Instead of shifting off the first element of
C<@_> into C<$self> (as C<method> does), it shifts off I<two> values:
around foo($x, $y, $z) {
...
}
works like
&around('foo', sub :method {
my $orig = shift;
my $self = shift;
my ($x, $y, $z) = @_;
...
});
(except you also get the usual C<Function::Parameters> features such as
checking the number of arguments, etc).
C<$orig> and C<$self> both count as invocants and you can override their names
like this:
around foo($original, $object: $x, $y, $z) {
# $original is a reference to the wrapped method;
# $object is the object we're being called on
...
}
If you use C<:> to pick your own invocant names in the parameter list of
C<around>, you must specify exactly two variables.
These modifiers also differ from C<fun> and C<method> (and C<sub>) in that they
require a function name (there are no anonymous method modifiers) and they
take effect at runtime, not compile time. When you say C<fun foo() {}>, the
C<foo> function is defined right after the closing C<}> of the function body is
parsed. But with e.g. C<before foo() {}>, the declaration becomes a normal
function call (to the C<before> function in the current package), which is
performed at runtime.
=head3 Prototypes and attributes
You can specify attributes (see L<perlsub/Subroutine Attributes>) for your
functions using the usual syntax:
fun deref($x) :lvalue {
${$x}
}
my $silly;
deref(\$silly) = 42;
To specify a prototype (see L<perlsub/Prototypes>), use the C<prototype>