Documentation for method
subst assembled from the following types:
multi method subst(Str: , , *)
Returns the invocant string where
$matcher is replaced by
$replacement (or the original string, if no match was found).
$matcher can be a Regex, or a literal
Str. Non-Str matcher arguments of type Cool are coerced to
Str for literal matching. If a Regex
$matcher is used, the
$/ special variable will be set to
Nil (if no matches occurred), a Match object, or a List of Match objects (if multi-match options like
:g are used).
my = "Some foo";my = .subst(/foo/, "string"); # gives 'Some string'.=subst(/foo/, "string"); # in-place substitution. $some-string is now 'Some string'
The replacement can be a Callable in which the current Match object will be placed in the
$/ variable, as well as the
$_ topic variable. Using a Callable as replacement is how you can refer to any of the captures created in the regex:
# Using capture from $/ variable (the $0 is the first positional capture)say 'abc123defg'.subst(/(\d+)/, );# OUTPUT: «abc before 123 after defg␤»# Using capture from $/ variable (the $<foo> is a named capture)say 'abc123defg'.subst(/=\d+/, );# OUTPUT: «abc before 123 after defg␤»# Using WhateverCode to operate on the Match given in $_:say 'abc123defg'.subst(/(\d+)/, "[ " ~ *.flip ~ " ]");# OUTPUT: «abc[ 321 ]defg␤»# Using a Callable to generate substitution without involving current Match:my = 41;my = "The answer is secret.";say .subst(/secret/, ); # The answer to everything# OUTPUT: «The answer is 42.␤»
Here are other examples of usage:
my = "Hey foo foo foo";.subst(/foo/, "bar", :g); # global substitution - returns Hey bar bar bar.subst(/foo/, "no subst", :x(0)); # targeted substitution. Number of times to substitute. Returns back unmodified..subst(/foo/, "bar", :x(1)); #replace just the first occurrence..subst(/foo/, "bar", :nth(3)); # replace nth match alone. Replaces the third foo. Returns Hey foo foo bar
:nth adverb has readable English-looking variants:
say 'ooooo'.subst: 'o', 'x', :1st; # OUTPUT: «xoooo␤»say 'ooooo'.subst: 'o', 'x', :2nd; # OUTPUT: «oxooo␤»say 'ooooo'.subst: 'o', 'x', :3rd; # OUTPUT: «ooxoo␤»say 'ooooo'.subst: 'o', 'x', :4th; # OUTPUT: «oooxo␤»
The following adverbs are supported
|:g||:global||tries to match as often as possible|
|:nth(Int|Callable|Whatever)||only substitute the nth match; aliases: :st, :nd, :rd, and :th|
|:ss||:samespace||preserves whitespace on substitution|
|:ii||:samecase||preserves case on substitution|
|:mm||:samemark||preserves character marks (e.g. 'ü' replaced with 'o' will result in 'ö')|
|:x(Int|Range|Whatever)||substitute exactly $x matches|
Note that only in the
:s. In the method form, the
:i modifiers must be added to the regex, not the
subst method call.