Skip to content

Commit 97cd5ed

Browse files
zostayAlexDaniel
authored andcommitted
Adding docs for the named parameter trap (#734)
1 parent 8053deb commit 97cd5ed

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

doc/Language/traps.pod6

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,52 @@ Finally, note that, currently, when declaring the functions whitespace
357357
may be used between a function or method name and the parentheses
358358
surrounding the parameter list without problems.
359359
360+
=head2 Named Parameters
361+
362+
Many built-in subroutines and method calls accept named parameters and your own
363+
code may accept them as well, but be sure the arguments you pass when calling
364+
your routines are actually named parameters:
365+
366+
sub foo($a, :$b) { ... }
367+
foo(1, 'b' => 2); # FAIL: Too many positionals passed; expected 1 argument but got 2
368+
369+
What happened? That second argument is not a named parameter argument, but a
370+
L<Pair|/type/Pair> passed as a positional argument. If you want a named
371+
parameter it has to look like a name to Perl:
372+
373+
foo(1, b => 2); # okay
374+
foo(1, :b(2); # okay
375+
foo(1, :b<it>); # okay
376+
377+
my $b = 2;
378+
foo(1, :b($b)); # okay, but redundant
379+
foo(1, :$b); # okay
380+
381+
# Or even...
382+
my %arg = 'b' => 2;
383+
foo(1, |%arg); # okay too
384+
385+
That last one may be confusing, but since it uses the C<|> prefix on a
386+
L<Hash|/type/Hash>, it means "treat this hash as holding named arguments."
387+
388+
If you really do want to pass them as pairs you should use a L<List|/type/List>
389+
or L<Capture|/type/Capture> instead:
390+
391+
my $list = ('b' => 2); # this is a List containing a single Pair
392+
foo(|$arg, :$b); # okay: we passed the pair 'b' => 2 to the first argument
393+
foo(1, |$arg); # FAIL: Too many positionals passed; expected 1 argument but got 2
394+
395+
my $cap = \('b' => 2); # a Capture with a single positional value
396+
foo(|$cap, :$b); # okay: we passed the pair 'b' => 2 to the first argument
397+
foo(1, |$cap); # FAIL: Too many positionals passed; expected 1 argument but got 2
398+
399+
A Capture is usually the best option for this as it works exactly like the usual
400+
capturing of routine arguments during a regular call.
401+
402+
The nice thing about the distinction here is that it gives the developer the
403+
option of passing pairs as either named or positional arguments, which can be
404+
handy in various instances.
405+
360406
=end pod
361407

362408
# vim: expandtab shiftwidth=4 ft=perl6

0 commit comments

Comments
 (0)