s///

Documentation for s/// assembled from the following types:

language documentation Operators

From Operators

(Operators) s///

my $str = 'old string';
$str ~~ s/.+ d/new/;
say $str# 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 $str = 'foo muCKed into the lEn';
 
# replace second 'o' with 'x' 
$str ~~ s:2nd/o/x/;
 
# replace 'M' or 'L' followed by non-whitespace stuff with 'd' 
# and lower-cased version of that stuff: 
$str ~~ s :g :i/<[ML]> (\S+)/d{lc $0}/;
 
say $str# OUTPUT: «fox ducked into the den␤» 

You can also use a different delimiter:

my $str = 'foober';
$str ~~ s!foo!fox!;
$str ~~ s{b(.)r} = " d$0n";
say $str# 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.).