Skip to Content
Learning Perl, 7th Edition
book

Learning Perl, 7th Edition

by Randal L. Schwartz, brian d foy, Tom Phoenix
October 2016
Beginner
391 pages
10h 38m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 7th Edition

Chapter 9. Processing Text with Regular Expressions

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.

Substitutions with s///

If you think of the m// 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.";
s/Barney/Fred/;  # Replace Barney with Fred
print "$_\n";
Note

Unlike m//, which can match against any string expression, s/// is modifying data that must therefore be contained in what’s known as an lvalue. This is nearly always a variable, but could be anything you can use on the left side of an assignment operator.

If the match fails, nothing happens, and the variable is untouched:

# Continuing from previous; $_ has "He's out bowling with Fred tonight."
s/Wilma/Betty/;  # 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 variable, $1, which is set by the pattern match:

s/with (\w+)/against $1's team/;
print "$_\n";  # 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 ...

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.
Start your free trial

You might also like

Mastering Perl, 2nd Edition

Mastering Perl, 2nd Edition

brian d foy
Perl One-Liners

Perl One-Liners

Peteris Krumins
Learning Perl, 8th Edition

Learning Perl, 8th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Programming Perl, 4th Edition

Programming Perl, 4th Edition

Tom Christiansen, brian d foy, Larry Wall, Jon Orwant

Publisher Resources

ISBN: 9781491954317Errata Page