You can use regular expressions to change text too. So far we’ve only shown you how to match a pattern, and now we’ll show you how to use patterns to locate the parts of strings that you want to change.
If you think of the
pattern match as being like your word processor’s “search” feature, the
“search and replace” feature would be Perl’s
s/// substitution operator. This simply
replaces whatever part of a variable matches the pattern with a replacement string:
"He's out bowling with Barney tonight."
# Replace Barney with Fred
If the match fails, nothing happens, and the variable is untouched:
# Continuing from above; $_ has "He's out bowling with Fred tonight."
# Replace Wilma with Betty (fails)
Of course, both the pattern and the replacement string could be
more complex. Here, the replacement string uses the first capture
$1, which is set by the
s/with (\w+)/against $1's team/
# says "He's out bowling against Fred's team tonight."
Here are some other possible substitutions. These are here only as samples; in the real world, it would not be typical to do so many unrelated substitutions in a row:
"green scaly dinosaur"
s/(\w+) (\w+)/$2, $1/
# Now it's "scaly, green dinosaur"
# Now it's "huge, scaly, green dinosaur"
# Empty replacement: Now it's "huge dinosaur"
# Failed match: ...