@@ -357,6 +357,52 @@ Finally, note that, currently, when declaring the functions whitespace
357
357
may be used between a function or method name and the parentheses
358
358
surrounding the parameter list without problems.
359
359
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
+
360
406
= end pod
361
407
362
408
# vim: expandtab shiftwidth=4 ft=perl6
0 commit comments