In Signature literals§
See primary documentation in context for Capture parameters.
Prefixing a parameter with a vertical bar | makes the parameter a Capture, using up all the remaining positional and named arguments.
sub a(Int $i, |cap) { say $i; say cap.gist } a(42, universe => 41, 1, 2, 3); # OUTPUT: ›42\(1, 2, 3, :universe(41))»
Arguments captured to a variable can be forwarded as a whole using the slip operator |.
sub b(Int $i, Str $s) { say $i.^name ~ ' ' ~ $s.^name } sub c(|cap) { say cap.^name; b(|cap) } c(42, "answer"); # OUTPUT: «CaptureInt Str»
One can also constrain the arguments subject to a Capture by using a sub-signature.
sub d(|cap(Int, Str, *%)) { put "called with {cap.raku}" }; d(41); # OUTPUT: «Too few positionals passed to 'd'; expected 2 arguments but got 1 in sub-signature or parameter cap ...»
Unbound Captures are often used in proto definitions (like proto foo (|) {*}) to indicate that the routine's multi definitions can have any type constraints. See proto for an example.
In Regexes§
See primary documentation in context for Longest alternation: |.
In short, in regex branches separated by |, the longest token match wins, independent of the textual ordering in the regex. However, what | really does is more than that. It does not decide which branch wins after finishing the whole match, but follows the longest-token matching (LTM) strategy.
Briefly, what | does is this:
First, select the branch which has the longest declarative prefix.
say "abc" ~~ /ab | a.* /; # OUTPUT: «⌜abc⌟» say "abc" ~~ /ab | a {} .* /; # OUTPUT: «⌜ab⌟» say "if else" ~~ / if | if <.ws> else /; # OUTPUT: «「if」» say "if else" ~~ / if | if \s+ else /; # OUTPUT: «「if else」»
As is shown above, a.* is a declarative prefix, while a {} .* terminates at {}, then its declarative prefix is a. Note that non-declarative atoms terminate declarative prefix. This is quite important if you want to apply | in a rule, which automatically enables :s, and <.ws> accidentally terminates declarative prefix.
If it's a tie, select the match with the highest specificity.
say "abc" ~~ /a. | ab { print "win" } /; # OUTPUT: «win「ab」»
When two alternatives match at the same length, the tie is broken by specificity. That is, ab, as an exact match, counts as closer than a., which uses character classes.
If it's still a tie, use additional tie-breakers.
say "abc" ~~ /a\w| a. { print "lose" } /; # OUTPUT: «⌜ab⌟»
If the tie breaker above doesn't work, then the textually earlier alternative takes precedence.
For more details, see the LTM strategy.