1 package Function::Parameters;
11 our $VERSION = '1.00_01';
12 our $XS_VERSION = $VERSION;
13 $VERSION = eval $VERSION;
17 sub _assert_valid_identifier {
18 my ($name, $with_dollar) = @_;
19 my $bonus = $with_dollar ? '\$' : '';
20 $name =~ /^${bonus}[^\W\d]\w*\z/
21 or confess qq{"$name" doesn't look like a valid identifier};
24 sub _assert_valid_attributes {
26 $attrs =~ /^\s*:\s*[^\W\d]\w*\s*(?:(?:\s|:\s*)[^\W\d]\w*\s*)*(?:\(|\z)/
27 or confess qq{"$attrs" doesn't look like valid attributes};
30 my @bare_arms = qw(function method);
34 default_arguments => 1,
35 check_argument_count => 0,
36 named_parameters => 1,
40 default_arguments => 1,
41 check_argument_count => 0,
42 named_parameters => 1,
49 default_arguments => 1,
50 check_argument_count => 0,
51 named_parameters => 1,
52 attributes => ':method',
57 for my $k (keys %type_map) {
58 $type_map{$k . '_strict'} = {
60 check_argument_count => 1,
73 if (@_ == 1 && $_[0] eq ':strict') {
75 fun => 'function_strict',
76 method => 'method_strict',
79 if (@_ == 1 && ref($_[0]) eq 'HASH') {
80 @_ = map [$_, $_[0]{$_}], keys %{$_[0]};
89 : [$proto, $bare_arms[$bare++] || confess(qq{Don't know what to do with "$proto"})]
91 my ($name, $proto_type) = @$item;
92 _assert_valid_identifier $name;
94 unless (ref $proto_type) {
95 # use '||' instead of 'or' to preserve $proto_type in the error message
96 $proto_type = $type_map{$proto_type}
97 || confess qq["$proto_type" doesn't look like a valid type (one of ${\join ', ', sort keys %type_map})];
100 my %type = %$proto_type;
103 $clean{name} = delete $type{name} || 'optional';
104 $clean{name} =~ /^(?:optional|required|prohibited)\z/
105 or confess qq["$clean{name}" doesn't look like a valid name attribute (one of optional, required, prohibited)];
107 $clean{shift} = delete $type{shift} || '';
108 _assert_valid_identifier $clean{shift}, 1 if $clean{shift};
110 $clean{attrs} = join ' ', map delete $type{$_} || (), qw(attributes attrs);
111 _assert_valid_attributes $clean{attrs} if $clean{attrs};
113 $clean{default_arguments} =
114 exists $type{default_arguments}
115 ? !!delete $type{default_arguments}
118 $clean{check_argument_count} = !!delete $type{check_argument_count};
119 $clean{invocant} = !!delete $type{invocant};
120 $clean{named_parameters} = !!delete $type{named_parameters};
122 %type and confess "Invalid keyword property: @{[keys %type]}";
124 $spec{$name} = \%clean;
127 for my $kw (keys %spec) {
128 my $type = $spec{$kw};
131 $type->{name} eq 'prohibited' ? FLAG_ANON_OK :
132 $type->{name} eq 'required' ? FLAG_NAME_OK :
133 FLAG_ANON_OK | FLAG_NAME_OK
135 $flags |= FLAG_DEFAULT_ARGS if $type->{default_arguments};
136 $flags |= FLAG_CHECK_NARGS if $type->{check_argument_count};
137 $flags |= FLAG_INVOCANT if $type->{invocant};
138 $flags |= FLAG_NAMED_PARAMS if $type->{named_parameters};
139 $^H{HINTK_FLAGS_ . $kw} = $flags;
140 $^H{HINTK_SHIFT_ . $kw} = $type->{shift};
141 $^H{HINTK_ATTRS_ . $kw} = $type->{attrs};
142 $^H{+HINTK_KEYWORDS} .= "$kw ";
150 delete $^H{+HINTK_KEYWORDS};
155 $^H{+HINTK_KEYWORDS} =~ s/(?<![^ ])\Q$kw\E //g;
168 Function::Parameters - subroutine definitions with parameter lists
172 use Function::Parameters qw(:strict);
175 fun foo($bar, $baz) {
179 # function with prototype
180 fun mymap($fun, @args)
185 push @res, $fun->($_);
190 print "$_\n" for mymap { $_ * 2 } 1 .. 4;
192 # method with implicit $self
193 method set_name($name) {
194 $self->{name} = $name;
197 # method with explicit invocant
198 method new($class: %init) {
199 return bless { %init }, $class;
202 # function with optional parameters
203 fun search($haystack, $needle = qr/^(?!)/, $offset = 0) {
207 # method with named parameters
208 method resize(:$width, :$height) {
209 $self->{width} = $width;
210 $self->{height} = $height;
213 $obj->resize(height => 4, width => 5);
215 # function with named optional parameters
216 fun search($haystack, :$needle = qr/^(?!)/, :$offset = 0) {
220 my $results = search $text, offset => 200;
224 This module extends Perl with keywords that let you define functions with
225 parameter lists. It uses Perl's L<keyword plugin|perlapi/PL_keyword_plugin>
226 API, so it works reliably and doesn't require a source filter.
230 The anatomy of a function (as recognized by this module):
236 The keyword introducing the function.
240 The function name (optional).
244 The parameter list (optional).
248 The prototype (optional).
252 The attribute list (optional).
262 # (1) (2) (3) (4) (5) (6)
263 fun foo ($x, $y) :($$) :lvalue { ... }
268 In the following section I'm going to describe all parts in order from simplest to most complex.
272 This is just a normal block of statements, as with L<C<sub>|perlsub>. No surprises here.
276 If present, it specifies the name of the function being defined. As with
277 L<C<sub>|perlsub>, if a name is present, the whole declaration is syntactically
278 a statement and its effects are performed at compile time (i.e. at runtime you
279 can call functions whose definitions only occur later in the file). If no name
280 is present, the declaration is an expression that evaluates to a reference to
281 the function in question. No surprises here either.
285 Attributes are relatively unusual in Perl code, but if you want them, they work
286 exactly the same as with L<C<sub>|perlsub/Subroutine-Attributes>.
290 As with L<C<sub>|perlsub/Prototypes>, a prototype, if present, contains hints as to how
291 the compiler should parse calls to this function. This means prototypes have no
292 effect if the function call is compiled before the function declaration has
293 been seen by the compiler or if the function to call is only determined at
294 runtime (e.g. because it's called as a method or through a reference).
296 With L<C<sub>|perlsub>, a prototype comes directly after the function name (if
297 any). C<Function::Parameters> reserves this spot for the
298 L<parameter list|/"Parameter list">. To specify a prototype, put it as the
299 first attribute (e.g. C<fun foo :(&$$)>). This is syntactically unambiguous
300 because normal L<attributes|/Attributes> need a name after the colon.
302 =head3 Parameter list
304 The parameter list is a list of variables enclosed in parentheses, except it's
305 actually a bit more complicated than that. A parameter list can include the
306 following 6 parts, all of which are optional:
312 This is a scalar variable followed by a colon (C<:>) and no comma. If an
313 invocant is present in the parameter list, the first element of
314 L<C<@_>|perlvar/@ARG> is automatically L<C<shift>ed|perlfunc/shift> off and
315 placed in this variable. This is intended for methods:
317 method new($class: %init) {
318 return bless { %init }, $class;
321 method throw($self:) {
325 =item 2. Required positional parameters
327 The most common kind of parameter. This is simply a comma-separated list of
328 scalars, which are filled from left to right with the arguments that the caller
337 =item 3. Optional positional parameters
339 Parameters can be marked as optional by putting an equals sign (C<=>) and an
340 expression (the "default argument") after them. If no corresponding argument is
341 passed in by the caller, the default argument will be used to initialize the
344 fun scale($base, $factor = 2) {
345 return $base * $factor;
348 say scale(3, 5); # "15"
351 The default argument is I<not> cached. Every time a function is called with
352 some optional arguments missing, the corresponding default arguments are
353 evaluated from left to right. This makes no difference for a value like C<2>
354 but it is important for expressions with side effects, such as reference
355 constructors (C<[]>, C<{}>) or function calls.
357 Default arguments see not only the surrounding lexical scope of their function
358 but also any preceding parameters. This allows the creation of dynamic defaults
359 based on previous arguments:
361 method set_name($self: $nick = $self->default_nick, $real_name = $nick) {
362 $self->{nick} = $nick;
363 $self->{real_name} = $real_name;
366 $obj->set_name("simplicio"); # same as: $obj->set_name("simplicio", "simplicio");
368 Because default arguments are actually evaluated as part of the function body,
369 you can also do silly things like this:
371 fun foo($n = return "nope") {
375 say foo(2 + 2); # "you gave me 4"
378 =item 4. Required named parameters
380 By putting a colon (C<:>) in front of a parameter you can make it named
381 instead of positional:
383 fun rectangle(:$width, :$height) {
387 rectangle(width => 2, height => 5);
388 rectangle(height => 5, width => 2); # same thing!
390 That is, the caller must specify a key name in addition to the value, but in
391 exchange the order of the arguments doesn't matter anymore. As with hash
392 initialization, you can specify the same key multiple times and the last
395 rectangle(height => 1, width => 2, height => 2, height => 5;
396 # same as: rectangle(width => 2, height => 5);
398 You can combine positional and named parameters as long as the positional
399 parameters come first:
401 fun named_rectangle($name, :$width, :$height) {
405 named_rectangle("Avocado", width => 0.5, height => 1.2);
407 =item 5. Optional named parameters
409 As with positional parameters, you can make named parameters optional by
410 specifying a default argument after an equals sign (C<=>):
412 fun rectangle(:$width, :$height, :$color = "chartreuse") {
416 rectangle(height => 10, width => 5);
417 # same as: rectangle(height => 10, width => 5, color => "chartreuse");
423 fun get($url, :$cookie_jar = HTTP::Cookies->new(), :$referrer = $url) {
427 my $data = get "http://www.example.com/", referrer => undef; # overrides $referrer = $url
429 The above example shows that passing any value (even C<undef>) will override
430 the default argument.
432 =item 6. Slurpy parameter
434 Finally you can put an array or hash in the parameter list, which will gobble
435 up the remaining arguments (if any):
437 fun foo($x, $y, @rest) { ... }
439 foo "a", "b"; # $x = "a", $y = "b", @rest = ()
440 foo "a", "b", "c"; # $x = "a", $y = "b", @rest = ("c")
441 foo "a", "b", "c", "d"; # $x = "a", $y = "b", @rest = ("c", "d")
443 If you combine this with named parameters, the slurpy parameter will end up
444 containing all unrecognized keys:
446 fun bar(:$size, @whatev) { ... }
448 bar weight => 20, size => 2, location => [0, -3];
449 # $size = 2, @whatev = ('weight', 20, 'location', [0, -3])
453 Apart from the L<C<shift>|perlfunc/shift> performed by the L<invocant|/"1.
454 Invocant">, all of the above leave L<C<@_>|perlvar/@ARG> unchanged; and if you
455 don't specify a parameter list at all, L<C<@_>|perlvar/@ARG> is all you get.
459 The keywords provided by C<Function::Parameters> are customizable. Since
460 C<Function::Parameters> is actually a L<pragma|perlpragma>, the provided
461 keywords have lexical scope. The following import variants can be used:
465 =item C<use Function::Parameters ':strict'>
467 Provides the keywords C<fun> and C<method> (described below) and enables
468 argument checks so that calling a function and omitting a required argument (or
469 passing too many arguments) will throw an error.
471 =item C<use Function::Parameters>
473 Provides the keywords C<fun> and C<method> (described below) and enables
474 "lax" mode: Omitting a required argument sets it to C<undef> while excess
475 arguments are silently ignored.
477 =item C<< use Function::Parameters { KEYWORD1 => TYPE1, KEYWORD2 => TYPE2, ... } >>
479 Provides completely custom keywords as described by their types. A "type" is
480 either a string (one of the predefined types C<function>, C<method>,
481 C<classmethod>, C<function_strict>, C<method_strict>, C<classmethod_strict>) or
482 a reference to a hash with the following keys:
488 Valid values: C<optional> (default), C<required> (all functions defined with
489 this keyword must have a name), and C<prohibited> (functions defined with this
490 keyword must be anonymous).
494 Valid values: strings that look like scalar variables. This lets you specify a
495 default L<invocant|/"1. Invocant">, i.e. a function defined with this keyword
496 that doesn't have an explicit invocant in its parameter list will automatically
497 L<C<shift>|perlfunc/shift> its first argument into the variable specified here.
501 Valid values: booleans. If you set this to a true value, the keyword will
502 accept L<invocants|/"1. Invocant"> in parameter lists; otherwise specifying
503 an invocant in a function defined with this keyword is a syntax error.
507 Valid values: strings containing (source code for) attributes. This causes any
508 function defined with this keyword to have the specified
509 L<attributes|attributes> (in addition to any attributes specified in the
510 function definition itself).
512 =item C<default_arguments>
514 Valid values: booleans. This property is on by default; use
515 C<< default_arguments => 0 >> to turn it off. This controls whether optional
516 parameters are allowed. If it is turned off, using C<=> in parameter lists is
519 =item C<check_argument_count>
521 Valid values: booleans. If turned on, functions defined with this keyword will
522 automatically check that they have been passed all required arguments and no
523 excess arguments. If this check fails, an exception will by thrown via
524 L<C<Carp::croak>|Carp>.
528 The predefined type C<function> is equivalent to:
533 default_arguments => 1,
534 check_argument_count => 0,
537 These are all default values, so C<function> is also equivalent to C<{}>.
539 C<method> is equivalent to:
545 attributes => ':method',
546 default_arguments => 1,
547 check_argument_count => 0,
551 C<classmethod> is equivalent to:
557 attributes => ':method',
558 default_arguments => 1,
559 check_argument_count => 0,
562 C<function_strict>, C<method_strict>, and
563 C<classmethod_strict> are like C<function>, C<method>, and
564 C<classmethod>, respectively, but with C<< check_argument_count => 1 >>.
568 Plain C<use Function::Parameters> is equivalent to
569 C<< use Function::Parameters { fun => 'function', method => 'method' } >>.
571 C<use Function::Parameters qw(:strict)> is equivalent to
572 C<< use Function::Parameters { fun => 'function_strict', method => 'method_strict' } >>.
574 =head2 Wrapping C<Function::Parameters>
576 If you want to write a wrapper around C<Function::Parameters>, you only have to
577 call its C<import> method. Due to its L<pragma|perlpragma> nature it always
578 affects the file that is currently being compiled.
580 package Some::Wrapper;
581 use Function::Parameters ();
583 Function::Parameters->import;
584 # or Function::Parameters->import(@custom_import_args);
589 The module is actually written in L<C|perlxs> and uses
590 L<C<PL_keyword_plugin>|perlapi/PL_keyword_plugin> to generate opcodes directly.
591 However, you can run L<C<perl -MO=Deparse ...>|B::Deparse> on your code to see
592 what happens under the hood. In the simplest case (no argument checks, possibly
593 an L<invocant|/"1. Invocant">, required positional/slurpy parameters only), the
594 generated code corresponds to:
596 fun foo($x, $y, @z) { ... }
598 sub foo { my ($x, $y, @z) = @_; sub foo; ... }
600 method bar($x, $y, @z) { ... }
602 sub bar :method { my $self = shift; my ($x, $y, @z) = @_; sub bar; ... }
606 Lukas Mai, C<< <l.mai at web.de> >>
608 =head1 COPYRIGHT & LICENSE
610 Copyright 2010, 2011, 2012 Lukas Mai.
612 This program is free software; you can redistribute it and/or modify it
613 under the terms of either: the GNU General Public License as published
614 by the Free Software Foundation; or the Artistic License.
616 See http://dev.perl.org/licenses/ for more information.