syntax s///
Documentation for syntax s///
assembled from the following types:
language documentation Operators
From Operators
(Operators) s///
my = 'old string';~~ s/o .+ d/new/;say ; # OUTPUT: «new string»
s///
operates on the $_
topical variable, changing it in place. It uses the given Regex
to find portions to replace and changes them to the provided replacement string. Sets $/
to the Match
object or, if multiple matches were made, a List
of Match
objects. Returns $/
.
It's common to use this operator with the ~~
smartmatch operator, as it aliases left-hand side to $_
, which s///
uses.
Regex captures can be referenced in the replacement part; it takes the same adverbs as the .subst
method, which go between the s
and the opening /
, separated with optional whitespace:
my = 'foo muCKed into the lEn';# replace second 'o' with 'x'~~ s:2nd/o/x/;# replace 'M' or 'L' followed by non-whitespace stuff with 'd'# and lower-cased version of that stuff:~~ s :g :i/ (\S+)/d/;say ; # OUTPUT: «fox ducked into the den»
You can also use a different delimiter:
my = 'foober';~~ s!foo!fox!;~~ s{b(.)r} = " d$0n";say ; # OUTPUT: «fox den»
Non-paired characters can simply replace the original slashes. Paired characters, like curly braces, are used only on the match portion, with the substitution given by assignment (of anything: a string, a routine call, etc.).