Using Patterns for Search and Replace

One of the niftiest uses of regular expressions involves not just searching for a pattern or extracting matches into lists or variables or whatever, but also replacing that pattern with some other string. This is equivalent to a search and replace in your favorite word processor or editor—only with all the power and flexibility that regular expressions give you.

To search for a pattern and then replace it with some other pattern, use this syntax:

s/pattern/replacement/

For this syntax the pattern is some form of regular expression; replacement is the string that will replace the match. A missing replacement will delete the match from the string. For example:

 s/\s+/ / # replace one or more whitespace characters ...

Get Sams Teach Yourself Perl in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.