The s/// Operator (Substitution)
s/PATTERN/REPLACEMENT/modifiersLVALUE=~ s/PATTERN/REPLACEMENT/modifiersRVALUE=~ s/PATTERN/REPLACEMENT/rmodifiers
This operator searches a string for PATTERN
and, if found, replaces the matched substring with the
REPLACEMENT text. If
PATTERN is a null string, the last
successfully executed regular expression is used instead.
$lotr = $hobbit; # Just copy The Hobbit $lotr =~ s/Bilbo/Frodo/g; # and write a sequel the easy way.
If the /r modifier is used, the
return value of an s/// operation is
the result string, and the target string is left unchanged. Without the
/r modifier, the return value of an
s/// operation (in scalar and list
context alike) is the number of times it succeeded—which can be more
than once if used with the /g
modifier, as described earlier. On failure, since it substituted zero
times, it returns false (""), which
is numerically equivalent to 0.[93]
if ($lotr =~ s/Bilbo/Frodo/) { say "Successfully wrote sequel." }
$change_count = $lotr =~ s/Bilbo/Frodo/g;Normally, everything matched by the
PATTERN is discarded on each substitution,
but you can “keep” part of that by including \K in your pattern:
$tales_of_Rohan =~ s/Éo\Kmer/wyn/g; # rewriting history
The replacement portion is treated as a double-quoted string. You
may use any of the dynamically scoped pattern variables described
earlier ($`, $&, $',
$1, $2, and so on) in the replacement string, as well as any other double-quote gizmos you care to employ. For instance, here’s an example ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access