1 package Function::Parameters;
11 our $VERSION = '1.00';
15 sub _assert_valid_identifier {
16 my ($name, $with_dollar) = @_;
17 my $bonus = $with_dollar ? '\$' : '';
18 $name =~ /^${bonus}[^\W\d]\w*\z/
19 or confess qq{"$name" doesn't look like a valid identifier};
22 sub _assert_valid_attributes {
24 $attrs =~ /^\s*:\s*[^\W\d]\w*\s*(?:(?:\s|:\s*)[^\W\d]\w*\s*)*(?:\(|\z)/
25 or confess qq{"$attrs" doesn't look like valid attributes};
28 my @bare_arms = qw(function method);
32 default_arguments => 1,
33 check_argument_count => 0,
34 named_parameters => 1,
38 default_arguments => 1,
39 check_argument_count => 0,
40 named_parameters => 1,
47 default_arguments => 1,
48 check_argument_count => 0,
49 named_parameters => 1,
50 attributes => ':method',
55 for my $k (keys %type_map) {
56 $type_map{$k . '_strict'} = {
58 check_argument_count => 1,
71 if (@_ == 1 && $_[0] eq ':strict') {
73 fun => 'function_strict',
74 method => 'method_strict',
77 if (@_ == 1 && ref($_[0]) eq 'HASH') {
78 @_ = map [$_, $_[0]{$_}], keys %{$_[0]};
87 : [$proto, $bare_arms[$bare++] || confess(qq{Don't know what to do with "$proto"})]
89 my ($name, $proto_type) = @$item;
90 _assert_valid_identifier $name;
92 unless (ref $proto_type) {
93 # use '||' instead of 'or' to preserve $proto_type in the error message
94 $proto_type = $type_map{$proto_type}
95 || confess qq["$proto_type" doesn't look like a valid type (one of ${\join ', ', sort keys %type_map})];
98 my %type = %$proto_type;
101 $clean{name} = delete $type{name} || 'optional';
102 $clean{name} =~ /^(?:optional|required|prohibited)\z/
103 or confess qq["$clean{name}" doesn't look like a valid name attribute (one of optional, required, prohibited)];
105 $clean{shift} = delete $type{shift} || '';
106 _assert_valid_identifier $clean{shift}, 1 if $clean{shift};
108 $clean{attrs} = join ' ', map delete $type{$_} || (), qw(attributes attrs);
109 _assert_valid_attributes $clean{attrs} if $clean{attrs};
111 $clean{default_arguments} =
112 exists $type{default_arguments}
113 ? !!delete $type{default_arguments}
116 $clean{check_argument_count} = !!delete $type{check_argument_count};
117 $clean{invocant} = !!delete $type{invocant};
118 $clean{named_parameters} = !!delete $type{named_parameters};
120 %type and confess "Invalid keyword property: @{[keys %type]}";
122 $spec{$name} = \%clean;
125 for my $kw (keys %spec) {
126 my $type = $spec{$kw};
129 $type->{name} eq 'prohibited' ? FLAG_ANON_OK :
130 $type->{name} eq 'required' ? FLAG_NAME_OK :
131 FLAG_ANON_OK | FLAG_NAME_OK
133 $flags |= FLAG_DEFAULT_ARGS if $type->{default_arguments};
134 $flags |= FLAG_CHECK_NARGS if $type->{check_argument_count};
135 $flags |= FLAG_INVOCANT if $type->{invocant};
136 $flags |= FLAG_NAMED_PARAMS if $type->{named_parameters};
137 $^H{HINTK_FLAGS_ . $kw} = $flags;
138 $^H{HINTK_SHIFT_ . $kw} = $type->{shift};
139 $^H{HINTK_ATTRS_ . $kw} = $type->{attrs};
140 $^H{+HINTK_KEYWORDS} .= "$kw ";
148 delete $^H{+HINTK_KEYWORDS};
153 $^H{+HINTK_KEYWORDS} =~ s/(?<![^ ])\Q$kw\E //g;
166 Function::Parameters - subroutine definitions with parameter lists
170 use Function::Parameters qw(:strict);
173 fun foo($bar, $baz) {
177 # function with prototype
178 fun mymap($fun, @args)
183 push @res, $fun->($_);
188 print "$_\n" for mymap { $_ * 2 } 1 .. 4;
190 # method with implicit $self
191 method set_name($name) {
192 $self->{name} = $name;
195 # method with explicit invocant
196 method new($class: %init) {
197 return bless { %init }, $class;
200 # function with optional parameters
201 fun search($haystack, $needle = qr/^(?!)/, $offset = 0) {
205 # method with named parameters
206 method resize(:$width, :$height) {
207 $self->{width} = $width;
208 $self->{height} = $height;
211 $obj->resize(height => 4, width => 5);
213 # function with named optional parameters
214 fun search($haystack, :$needle = qr/^(?!)/, :$offset = 0) {
218 my $results = search $text, offset => 200;
222 This module extends Perl with keywords that let you define functions with
223 parameter lists. It uses Perl's L<keyword plugin|perlapi/PL_keyword_plugin>
224 API, so it works reliably and doesn't require a source filter.
228 The anatomy of a function (as recognized by this module):
234 The keyword introducing the function.
238 The function name (optional).
242 The parameter list (optional).
246 The prototype (optional).
250 The attribute list (optional).
260 # (1) (2) (3) (4) (5) (6)
261 fun foo ($x, $y) :($$) :lvalue { ... }
266 In the following section I'm going to describe all parts in order from simplest to most complex.
270 This is just a normal block of statements, as with L<C<sub>|perlsub>. No surprises here.
274 If present, it specifies the name of the function being defined. As with
275 L<C<sub>|perlsub>, if a name is present, the whole declaration is syntactically
276 a statement and its effects are performed at compile time (i.e. at runtime you
277 can call functions whose definitions only occur later in the file). If no name
278 is present, the declaration is an expression that evaluates to a reference to
279 the function in question. No surprises here either.
283 Attributes are relatively unusual in Perl code, but if you want them, they work
284 exactly the same as with L<C<sub>|perlsub/Subroutine-Attributes>.
288 As with L<C<sub>|perlsub/Prototypes>, a prototype, if present, contains hints as to how
289 the compiler should parse calls to this function. This means prototypes have no
290 effect if the function call is compiled before the function declaration has
291 been seen by the compiler or if the function to call is only determined at
292 runtime (e.g. because it's called as a method or through a reference).
294 With L<C<sub>|perlsub>, a prototype comes directly after the function name (if
295 any). C<Function::Parameters> reserves this spot for the
296 L<parameter list|/"Parameter list">. To specify a prototype, put it as the
297 first attribute (e.g. C<fun foo :(&$$)>). This is syntactically unambiguous
298 because normal L<attributes|/Attributes> need a name after the colon.
300 =head3 Parameter list
302 The parameter list is a list of variables enclosed in parentheses, except it's
303 actually a bit more complicated than that. A parameter list can include the
304 following 6 parts, all of which are optional:
310 This is a scalar variable followed by a colon (C<:>) and no comma. If an
311 invocant is present in the parameter list, the first element of
312 L<C<@_>|perlvar/@ARG> is automatically L<C<shift>ed|perlfunc/shift> off and
313 placed in this variable. This is intended for methods:
315 method new($class: %init) {
316 return bless { %init }, $class;
319 method throw($self:) {
323 =item 2. Required positional parameters
325 The most common kind of parameter. This is simply a comma-separated list of
326 scalars, which are filled from left to right with the arguments that the caller
335 =item 3. Optional positional parameters
337 Parameters can be marked as optional by putting an equals sign (C<=>) and an
338 expression (the "default argument") after them. If no corresponding argument is
339 passed in by the caller, the default argument will be used to initialize the
342 fun scale($base, $factor = 2) {
343 return $base * $factor;
346 say scale(3, 5); # "15"
349 The default argument is I<not> cached. Every time a function is called with
350 some optional arguments missing, the corresponding default arguments are
351 evaluated from left to right. This makes no difference for a value like C<2>
352 but it is important for expressions with side effects, such as reference
353 constructors (C<[]>, C<{}>) or function calls.
355 Default arguments see not only the surrounding lexical scope of their function
356 but also any preceding parameters. This allows the creation of dynamic defaults
357 based on previous arguments:
359 method set_name($self: $nick = $self->default_nick, $real_name = $nick) {
360 $self->{nick} = $nick;
361 $self->{real_name} = $real_name;
364 $obj->set_name("simplicio"); # same as: $obj->set_name("simplicio", "simplicio");
366 Because default arguments are actually evaluated as part of the function body,
367 you can also do silly things like this:
369 fun foo($n = return "nope") {
373 say foo(2 + 2); # "you gave me 4"
376 =item 4. Required named parameters
378 By putting a colon (C<:>) in front of a parameter you can make it named
379 instead of positional:
381 fun rectangle(:$width, :$height) {
385 rectangle(width => 2, height => 5);
386 rectangle(height => 5, width => 2); # same thing!
388 That is, the caller must specify a key name in addition to the value, but in
389 exchange the order of the arguments doesn't matter anymore. As with hash
390 initialization, you can specify the same key multiple times and the last
393 rectangle(height => 1, width => 2, height => 2, height => 5;
394 # same as: rectangle(width => 2, height => 5);
396 You can combine positional and named parameters as long as the positional
397 parameters come first:
399 fun named_rectangle($name, :$width, :$height) {
403 named_rectangle("Avocado", width => 0.5, height => 1.2);
405 =item 5. Optional named parameters
407 As with positional parameters, you can make named parameters optional by
408 specifying a default argument after an equals sign (C<=>):
410 fun rectangle(:$width, :$height, :$color = "chartreuse") {
414 rectangle(height => 10, width => 5);
415 # same as: rectangle(height => 10, width => 5, color => "chartreuse");
421 fun get($url, :$cookie_jar = HTTP::Cookies->new(), :$referrer = $url) {
425 my $data = get "http://www.example.com/", referrer => undef; # overrides $referrer = $url
427 The above example shows that passing any value (even C<undef>) will override
428 the default argument.
430 =item 6. Slurpy parameter
432 Finally you can put an array or hash in the parameter list, which will gobble
433 up the remaining arguments (if any):
435 fun foo($x, $y, @rest) { ... }
437 foo "a", "b"; # $x = "a", $y = "b", @rest = ()
438 foo "a", "b", "c"; # $x = "a", $y = "b", @rest = ("c")
439 foo "a", "b", "c", "d"; # $x = "a", $y = "b", @rest = ("c", "d")
441 If you combine this with named parameters, the slurpy parameter will end up
442 containing all unrecognized keys:
444 fun bar(:$size, @whatev) { ... }
446 bar weight => 20, size => 2, location => [0, -3];
447 # $size = 2, @whatev = ('weight', 20, 'location', [0, -3])
451 Apart from the L<C<shift>|perlfunc/shift> performed by the L<invocant|/"1.
452 Invocant">, all of the above leave L<C<@_>|perlvar/@ARG> unchanged; and if you
453 don't specify a parameter list at all, L<C<@_>|perlvar/@ARG> is all you get.
457 The keywords provided by C<Function::Parameters> are customizable. Since
458 C<Function::Parameters> is actually a L<pragma|perlpragma>, the provided
459 keywords have lexical scope. The following import variants can be used:
463 =item C<use Function::Parameters ':strict'>
465 Provides the keywords C<fun> and C<method> (described below) and enables
466 argument checks so that calling a function and omitting a required argument (or
467 passing too many arguments) will throw an error.
469 =item C<use Function::Parameters>
471 Provides the keywords C<fun> and C<method> (described below) and enables
472 "lax" mode: Omitting a required argument sets it to C<undef> while excess
473 arguments are silently ignored.
475 =item C<< use Function::Parameters { KEYWORD1 => TYPE1, KEYWORD2 => TYPE2, ... } >>
477 Provides completely custom keywords as described by their types. A "type" is
478 either a string (one of the predefined types C<function>, C<method>,
479 C<classmethod>, C<function_strict>, C<method_strict>, C<classmethod_strict>) or
480 a reference to a hash with the following keys:
486 Valid values: C<optional> (default), C<required> (all functions defined with
487 this keyword must have a name), and C<prohibited> (functions defined with this
488 keyword must be anonymous).
492 Valid values: strings that look like scalar variables. This lets you specify a
493 default L<invocant|/"1. Invocant">, i.e. a function defined with this keyword
494 that doesn't have an explicit invocant in its parameter list will automatically
495 L<C<shift>|perlfunc/shift> its first argument into the variable specified here.
499 Valid values: booleans. If you set this to a true value, the keyword will
500 accept L<invocants|/"1. Invocant"> in parameter lists; otherwise specifying
501 an invocant in a function defined with this keyword is a syntax error.
505 Valid values: strings containing (source code for) attributes. This causes any
506 function defined with this keyword to have the specified
507 L<attributes|attributes> (in addition to any attributes specified in the
508 function definition itself).
510 =item C<default_arguments>
512 Valid values: booleans. This property is on by default; use
513 C<< default_arguments => 0 >> to turn it off. This controls whether optional
514 parameters are allowed. If it is turned off, using C<=> in parameter lists is
517 =item C<check_argument_count>
519 Valid values: booleans. If turned on, functions defined with this keyword will
520 automatically check that they have been passed all required arguments and no
521 excess arguments. If this check fails, an exception will by thrown via
522 L<C<Carp::croak>|Carp>.
526 The predefined type C<function> is equivalent to:
531 default_arguments => 1,
532 check_argument_count => 0,
535 These are all default values, so C<function> is also equivalent to C<{}>.
537 C<method> is equivalent to:
543 attributes => ':method',
544 default_arguments => 1,
545 check_argument_count => 0,
549 C<classmethod> is equivalent to:
555 attributes => ':method',
556 default_arguments => 1,
557 check_argument_count => 0,
560 C<function_strict>, C<method_strict>, and
561 C<classmethod_strict> are like C<function>, C<method>, and
562 C<classmethod>, respectively, but with C<< check_argument_count => 1 >>.
566 Plain C<use Function::Parameters> is equivalent to
567 C<< use Function::Parameters { fun => 'function', method => 'method' } >>.
569 C<use Function::Parameters qw(:strict)> is equivalent to
570 C<< use Function::Parameters { fun => 'function_strict', method => 'method_strict' } >>.
572 =head2 Wrapping C<Function::Parameters>
574 If you want to write a wrapper around C<Function::Parameters>, you only have to
575 call its C<import> method. Due to its L<pragma|perlpragma> nature it always
576 affects the file that is currently being compiled.
578 package Some::Wrapper;
579 use Function::Parameters ();
581 Function::Parameters->import;
582 # or Function::Parameters->import(@custom_import_args);
587 The module is actually written in L<C|perlxs> and uses
588 L<C<PL_keyword_plugin>|perlapi/PL_keyword_plugin> to generate opcodes directly.
589 However, you can run L<C<perl -MO=Deparse ...>|B::Deparse> on your code to see
590 what happens under the hood. In the simplest case (no argument checks, possibly
591 an L<invocant|/"1. Invocant">, required positional/slurpy parameters only), the
592 generated code corresponds to:
594 fun foo($x, $y, @z) { ... }
596 sub foo { my ($x, $y, @z) = @_; sub foo; ... }
598 method bar($x, $y, @z) { ... }
600 sub bar :method { my $self = shift; my ($x, $y, @z) = @_; sub bar; ... }
604 Lukas Mai, C<< <l.mai at web.de> >>
606 =head1 COPYRIGHT & LICENSE
608 Copyright 2010, 2011, 2012 Lukas Mai.
610 This program is free software; you can redistribute it and/or modify it
611 under the terms of either: the GNU General Public License as published
612 by the Free Software Foundation; or the Artistic License.
614 See http://dev.perl.org/licenses/ for more information.