Perl Operators   «Prev  Next»
Lesson 9Perl substitute operator
ObjectiveExamine the substitute operator.

Perl Substitute Operator

The substitute operator works just like the match operator, but with the addition of a replacement field. For example, the same program from the previous lesson could replace the word "hello" with "goodbye" like this:

#!/usr/bin/perl -w

while(<>) {
   s/hello/Goodbye/ig;
   print;
}

In this case, we have added the g switch so that replacements will be made globally, instead of on just the first occurrence on each line.

Substitute operator switches

The substitute operator has the same switches available as the match operator, with one addition.

Perl Substitute operator switches

Switch Meaning
i Ignore case
g Match globally, that is, find all occurrences, not just the first one
m Treat the string as multiple lines
o Only compile the pattern once
s Treat the string as a single line
x Use extended regular expressions
e Evaluate the replacement string as an expression

Regular Expressions
The e switch allows you to use the results of a Perl expression as your replacement. For example, if you wanted to replace all numbers with their hexadecimal equivalents, you could use this feature. In the next module, there will be some examples that use the e switch.

The substitution operation substitutes one expression for another; it uses the s// operator. The translation operation translates one set of characters to another and uses the tr// operator. All three regular expression operators work with $_ as the string to search. You can use the binding operators (see later in this section) to search a variable other than $_.
Both the matching (m//) and the substitution (s///) operators perform variable interpolation on the PATTERN and REPLACEMENT strings. This comes in handy if you need to read the pattern from the keyboard or a file.
If the match pattern evaluates to the empty string, the last valid pattern is used. So, if you see a statement like print if //; in a Perl program, look for the previous regular expression operator to see what the pattern really is. The substitution operator also uses this interpretation of the empty pattern.

The next stop on our tour of pattern-matching operators will be the translation operator. Please step this way to the following lesson.

Advanced Perl Programming