Lesson 9 | Selective replacement |
Objective | Examine how the s/// operator allows for selective text replacement. |
Perl Selective Replacement
Examine how the use of the s/// operator with subexpressions allows for selective text replacement.
The substitute operator also allows more selective replacements, using parenthesis to specify subexpressions.
Sub-expressions
Just as with the pattern-matching operator (m//), subexpressions surrounded by parenthesis on the left-hand side of a substitute operator (s///
)
are matched and placed in the special variables, $1
, $2
, $3
, and so on.
But in this case, you can use those variables on the right-hand side as part of the replacement.
For example, many people write the nonword alot when they mean to say a lot, (and they do it a lot). This expression can fix that:
s/(a)(lot)/$1 $2/ig
Whenever you want to use part of the matched expression in the replacement, subexpressions will help you. For example, some characters in a CGI query string are encoded in hexadecimal to prevent conflicts with the URL.
These hexadecimal numbers are always preceded by a %
character. The following regex decodes it:
s/%(..)/pack("c",hex($1))/ge;
In the next lesson, we will continue examining examples of selective replacement and then write a program that performs selective text replacement.