1 package Function::Parameters;
12 our $VERSION = 0.10_03;
16 sub _assert_valid_identifier {
17 my ($name, $with_dollar) = @_;
18 my $bonus = $with_dollar ? '\$' : '';
19 $name =~ /^${bonus}[^\W\d]\w*\z/
20 or confess qq{"$name" doesn't look like a valid identifier};
23 sub _assert_valid_attributes {
25 $attrs =~ /^\s*:\s*[^\W\d]\w*\s*(?:(?:\s|:\s*)[^\W\d]\w*\s*)*(?:\(|\z)/
26 or confess qq{"$attrs" doesn't look like valid attributes};
29 my @bare_arms = qw(function method);
33 default_arguments => 1,
34 check_argument_count => 0,
35 named_parameters => 1,
39 default_arguments => 1,
40 check_argument_count => 0,
41 named_parameters => 1,
48 default_arguments => 1,
49 check_argument_count => 0,
50 named_parameters => 1,
51 attributes => ':method',
56 for my $k (keys %type_map) {
57 $type_map{$k . '_strict'} = {
59 check_argument_count => 1,
72 if (@_ == 1 && $_[0] eq ':strict') {
74 fun => 'function_strict',
75 method => 'method_strict',
78 if (@_ == 1 && ref($_[0]) eq 'HASH') {
79 @_ = map [$_, $_[0]{$_}], keys %{$_[0]};
88 : [$proto, $bare_arms[$bare++] || confess(qq{Don't know what to do with "$proto"})]
90 my ($name, $proto_type) = @$item;
91 _assert_valid_identifier $name;
93 unless (ref $proto_type) {
94 # use '||' instead of 'or' to preserve $proto_type in the error message
95 $proto_type = $type_map{$proto_type}
96 || confess qq["$proto_type" doesn't look like a valid type (one of ${\join ', ', sort keys %type_map})];
99 my %type = %$proto_type;
102 $clean{name} = delete $type{name} || 'optional';
103 $clean{name} =~ /^(?:optional|required|prohibited)\z/
104 or confess qq["$clean{name}" doesn't look like a valid name attribute (one of optional, required, prohibited)];
106 $clean{shift} = delete $type{shift} || '';
107 _assert_valid_identifier $clean{shift}, 1 if $clean{shift};
109 $clean{attrs} = join ' ', map delete $type{$_} || (), qw(attributes attrs);
110 _assert_valid_attributes $clean{attrs} if $clean{attrs};
112 $clean{default_arguments} =
113 exists $type{default_arguments}
114 ? !!delete $type{default_arguments}
117 $clean{check_argument_count} = !!delete $type{check_argument_count};
118 $clean{invocant} = !!delete $type{invocant};
119 $clean{named_parameters} = !!delete $type{named_parameters};
121 %type and confess "Invalid keyword property: @{[keys %type]}";
123 $spec{$name} = \%clean;
126 for my $kw (keys %spec) {
127 my $type = $spec{$kw};
130 $type->{name} eq 'prohibited' ? FLAG_ANON_OK :
131 $type->{name} eq 'required' ? FLAG_NAME_OK :
132 FLAG_ANON_OK | FLAG_NAME_OK
134 $flags |= FLAG_DEFAULT_ARGS if $type->{default_arguments};
135 $flags |= FLAG_CHECK_NARGS if $type->{check_argument_count};
136 $flags |= FLAG_INVOCANT if $type->{invocant};
137 $flags |= FLAG_NAMED_PARAMS if $type->{named_parameters};
138 $^H{HINTK_FLAGS_ . $kw} = $flags;
139 $^H{HINTK_SHIFT_ . $kw} = $type->{shift};
140 $^H{HINTK_ATTRS_ . $kw} = $type->{attrs};
141 $^H{+HINTK_KEYWORDS} .= "$kw ";
149 delete $^H{+HINTK_KEYWORDS};
154 $^H{+HINTK_KEYWORDS} =~ s/(?<![^ ])\Q$kw\E //g;
167 Function::Parameters - subroutine definitions with parameter lists
171 use Function::Parameters qw(:strict);
174 fun foo($bar, $baz) {
178 # function with prototype
179 fun mymap($fun, @args)
184 push @res, $fun->($_);
189 print "$_\n" for mymap { $_ * 2 } 1 .. 4;
191 # method with implicit $self
192 method set_name($name) {
193 $self->{name} = $name;
196 # method with explicit invocant
197 method new($class: %init) {
198 return bless { %init }, $class;
201 # function with optional parameters
202 fun search($haystack, $needle = qr/^(?!)/, $offset = 0) {
206 # method with named parameters
207 method resize(:$width, :$height) {
208 $self->{width} = $width;
209 $self->{height} = $height;
212 $obj->resize(height => 4, width => 5);
214 # function with named optional parameters
215 fun search($haystack, :$needle = qr/^(?!)/, :$offset = 0) {
219 my $results = search $text, offset => 200;
223 This module extends Perl with keywords that let you define functions with
224 parameter lists. It uses Perl's L<keyword plugin|perlapi/PL_keyword_plugin>
225 API, so it works reliably and doesn't require a source filter.
229 The anatomy of a function (as recognized by this module):
235 The keyword introducing the function.
239 The function name (optional).
243 The parameter list (optional).
247 The prototype (optional).
251 The attribute list (optional).
261 # (1) (2) (3) (4) (5) (6)
262 fun foo ($x, $y) :($$) :lvalue { ... }
267 In the following section I'm going to describe all parts in order from simplest to most complex.
271 This is just a normal block of statements, as with L<C<sub>|perlsub>. No surprises here.
275 If present, it specifies the name of the function being defined. As with
276 L<C<sub>|perlsub>, if a name is present, the whole declaration is syntactically
277 a statement and its effects are performed at compile time (i.e. at runtime you
278 can call functions whose definitions only occur later in the file). If no name
279 is present, the declaration is an expression that evaluates to a reference to
280 the function in question. No surprises here either.
284 Attributes are relatively unusual in Perl code, but if you want them, they work
285 exactly the same as with L<C<sub>|perlsub/Subroutine-Attributes>.
289 As with L<C<sub>|perlsub/Prototypes>, a prototype, if present, contains hints as to how
290 the compiler should parse calls to this function. This means prototypes have no
291 effect if the function call is compiled before the function declaration has
292 been seen by the compiler or if the function to call is only determined at
293 runtime (e.g. because it's called as a method or through a reference).
295 With L<C<sub>|perlsub>, a prototype comes directly after the function name (if
296 any). C<Function::Parameters> reserves this spot for the
297 L<parameter list|/"Parameter list">. To specify a prototype, put it as the
298 first attribute (e.g. C<fun foo :(&$$)>). This is syntactically unambiguous
299 because normal L<attributes|/Attributes> need a name after the colon.
301 =head3 Parameter list
303 The parameter list is a list of variables enclosed in parentheses, except it's
304 actually a bit more complicated than that. A parameter list can include the
305 following 6 parts, all of which are optional:
311 This is a scalar variable followed by a colon (C<:>) and no comma. If an
312 invocant is present in the parameter list, the first element of
313 L<C<@_>|perlvar/@ARG> is automatically L<C<shift>ed|perlfunc/shift> off and
314 placed in this variable. This is intended for methods:
316 method new($class: %init) {
317 return bless { %init }, $class;
320 method throw($self:) {
324 =item 2. Required positional parameters
326 The most common kind of parameter. This is simply a comma-separated list of
327 scalars, which are filled from left to right with the arguments that the caller
336 =item 3. Optional positional parameters
338 Parameters can be marked as optional by putting an equals sign (C<=>) and an
339 expression (the "default argument") after them. If no corresponding argument is
340 passed in by the caller, the default argument will be used to initialize the
343 fun scale($base, $factor = 2) {
344 return $base * $factor;
347 say scale(3, 5); # "15"
350 The default argument is I<not> cached. Every time a function is called with
351 some optional arguments missing, the corresponding default arguments are
352 evaluated from left to right. This makes no difference for a value like C<2>
353 but it is important for expressions with side effects, such as reference
354 constructors (C<[]>, C<{}>) or function calls.
356 Default arguments see not only the surrounding lexical scope of their function
357 but also any preceding parameters. This allows the creation of dynamic defaults
358 based on previous arguments:
360 method set_name($self: $nick = $self->default_nick, $real_name = $nick) {
361 $self->{nick} = $nick;
362 $self->{real_name} = $real_name;
365 $obj->set_name("simplicio"); # same as: $obj->set_name("simplicio", "simplicio");
367 Because default arguments are actually evaluated as part of the function body,
368 you can also do silly things like this:
370 fun foo($n = return "nope") {
374 say foo(2 + 2); # "you gave me 4"
377 =item 4. Required named parameters
379 By putting a colon (C<:>) in front of a parameter you can make it named
380 instead of positional:
382 fun rectangle(:$width, :$height) {
386 rectangle(width => 2, height => 5);
387 rectangle(height => 5, width => 2); # same thing!
389 That is, the caller must specify a key name in addition to the value, but in
390 exchange the order of the arguments doesn't matter anymore. As with hash
391 initialization, you can specify the same key multiple times and the last
394 rectangle(height => 1, width => 2, height => 2, height => 5;
395 # same as: rectangle(width => 2, height => 5);
397 You can combine positional and named parameters as long as the positional
398 parameters come first:
400 fun named_rectangle($name, :$width, :$height) {
404 named_rectangle("Avocado", width => 0.5, height => 1.2);
406 =item 5. Optional named parameters
408 As with positional parameters, you can make named parameters optional by
409 specifying a default argument after an equals sign (C<=>):
411 fun rectangle(:$width, :$height, :$color = "chartreuse") {
415 rectangle(height => 10, width => 5);
416 # same as: rectangle(height => 10, width => 5, color => "chartreuse");
422 fun get($url, :$cookie_jar = HTTP::Cookies->new(), :$referrer = $url) {
426 my $data = get "http://www.example.com/", referrer => undef; # overrides $referrer = $url
428 The above example shows that passing any value (even C<undef>) will override
429 the default argument.
431 =item 6. Slurpy parameter
433 Finally you can put an array or hash in the parameter list, which will gobble
434 up the remaining arguments (if any):
436 fun foo($x, $y, @rest) { ... }
438 foo "a", "b"; # $x = "a", $y = "b", @rest = ()
439 foo "a", "b", "c"; # $x = "a", $y = "b", @rest = ("c")
440 foo "a", "b", "c", "d"; # $x = "a", $y = "b", @rest = ("c", "d")
442 If you combine this with named parameters, the slurpy parameter will end up
443 containing all unrecognized keys:
445 fun bar(:$size, @whatev) { ... }
447 bar weight => 20, size => 2, location => [0, -3];
448 # $size = 2, @whatev = ('weight', 20, 'location', [0, -3])
452 Apart from the L<C<shift>|perlfunc/shift> performed by the L<invocant|/"1.
453 Invocant">, all of the above leave L<C<@_>|perlvar/@ARG> unchanged; and if you
454 don't specify a parameter list at all, L<C<@_>|perlvar/@ARG> is all you get.
458 The keywords provided by C<Function::Parameters> are customizable. Since
459 C<Function::Parameters> is actually a L<pragma|perlpragma>, the provided
460 keywords have lexical scope. The following import variants can be used:
464 =item C<use Function::Parameters ':strict'>
466 Provides the keywords C<fun> and C<method> (described below) and enables
467 argument checks so that calling a function and omitting a required argument (or
468 passing too many arguments) will throw an error.
470 =item C<use Function::Parameters>
472 Provides the keywords C<fun> and C<method> (described below) and enables
473 "lax" mode: Omitting a required argument sets it to C<undef> while excess
474 arguments are silently ignored.
476 =item C<< use Function::Parameters { KEYWORD1 => TYPE1, KEYWORD2 => TYPE2, ... } >>
478 Provides completely custom keywords as described by their types. A "type" is
479 either a string (one of the predefined types C<function>, C<method>,
480 C<classmethod>, C<function_strict>, C<method_strict>, C<classmethod_strict>) or
481 a reference to a hash with the following keys:
487 Valid values: C<optional> (default), C<required> (all functions defined with
488 this keyword must have a name), and C<prohibited> (functions defined with this
489 keyword must be anonymous).
493 Valid values: strings that look like scalar variables. This lets you specify a
494 default L<invocant|/"1. Invocant">, i.e. a function defined with this keyword
495 that doesn't have an explicit invocant in its parameter list will automatically
496 L<C<shift>|perlfunc/shift> its first argument into the variable specified here.
500 Valid values: booleans. If you set this to a true value, the keyword will
501 accept L<invocants|/"1. Invocant"> in parameter lists; otherwise specifying
502 an invocant in a function defined with this keyword is a syntax error.
506 Valid values: strings containing (source code for) attributes. This causes any
507 function defined with this keyword to have the specified
508 L<attributes|attributes> (in addition to any attributes specified in the
509 function definition itself).
511 =item C<default_arguments>
513 Valid values: booleans. This property is on by default; use
514 C<< default_arguments => 0 >> to turn it off. This controls whether optional
515 parameters are allowed. If it is turned off, using C<=> in parameter lists is
518 =item C<check_argument_count>
520 Valid values: booleans. If turned on, functions defined with this keyword will
521 automatically check that they have been passed all required arguments and no
522 excess arguments. If this check fails, an exception will by thrown via
523 L<C<Carp::croak>|Carp>.
527 The predefined type C<function> is equivalent to:
532 default_arguments => 1,
533 check_argument_count => 0,
536 These are all default values, so C<function> is also equivalent to C<{}>.
538 C<method> is equivalent to:
544 attributes => ':method',
545 default_arguments => 1,
546 check_argument_count => 0,
550 C<classmethod> is equivalent to:
556 attributes => ':method',
557 default_arguments => 1,
558 check_argument_count => 0,
561 C<function_strict>, C<method_strict>, and
562 C<classmethod_strict> are like C<function>, C<method>, and
563 C<classmethod>, respectively, but with C<< check_argument_count => 1 >>.
567 Plain C<use Function::Parameters> is equivalent to
568 C<< use Function::Parameters { fun => 'function', method => 'method' } >>.
570 C<use Function::Parameters qw(:strict)> is equivalent to
571 C<< use Function::Parameters { fun => 'function_strict', method => 'method_strict' } >>.
573 =head2 Wrapping C<Function::Parameters>
575 If you want to write a wrapper around C<Function::Parameters>, you only have to
576 call its C<import> method. Due to its L<pragma|perlpragma> nature it always
577 affects the file that is currently being compiled.
579 package Some::Wrapper;
580 use Function::Parameters ();
582 Function::Parameters->import;
583 # or Function::Parameters->import(@custom_import_args);
588 The module is actually written in L<C|perlxs> and uses
589 L<C<PL_keyword_plugin>|perlapi/PL_keyword_plugin> to generate opcodes directly.
590 However, you can run L<C<perl -MO=Deparse ...>|B::Deparse> on your code to see
591 what happens under the hood. In the simplest case (no argument checks, possibly
592 an L<invocant|/"1. Invocant">, required positional/slurpy parameters only), the
593 generated code corresponds to:
595 fun foo($x, $y, @z) { ... }
597 sub foo { my ($x, $y, @z) = @_; sub foo; ... }
599 method bar($x, $y, @z) { ... }
601 sub bar :method { my $self = shift; my ($x, $y, @z) = @_; sub bar; ... }
605 Lukas Mai, C<< <l.mai at web.de> >>
607 =head1 COPYRIGHT & LICENSE
609 Copyright 2010, 2011, 2012 Lukas Mai.
611 This program is free software; you can redistribute it and/or modify it
612 under the terms of either: the GNU General Public License as published
613 by the Free Software Foundation; or the Artistic License.
615 See http://dev.perl.org/licenses/ for more information.