Regular Expressions   «Prev  Next»
Lesson 6 Substitution operator
Objective Examine structural details of using the substitution operator.

Perl Substitution Operator

In the next several lessons, we will cover the rest of the details about the substitution s// operator, which we introduced in the previous module, including how to use it for search-and-replace operations.
The s// operator searches a string for the pattern specified with the regex in the left-hand side of the operator (for example, between the first two delimiters). It then replaces the matched pattern with the string on the right-hand side (between the second and third delimiters).

For example,
 
while(<>) { 
 s/the/el/g; 
 print;
}


will replace every occurrence of the with el in the input stream.
The s// operator naturally binds to the special $_ variable, unless another variable is provided with one of the binding operators, =~ or !~. So if your intention is to operate on a particular variable, you must specify it with =~ or !~; for instance:

$pathname =~ s|^/|/var/web/|;

That will prepend /var/web/ to any pathnames that start with the root directory.
Note: Notice the use of | for delimiters to avoid a conflict with the slashes in the pathname. This is a very handy trick that you will want to use in an upcoming exercise.
The following is an example of when you might use alternative delimiters using the perl-e-modifier
In the next lesson, we will examine the modifiers that can be used with the s// operator.