Regular Expressions

Perl's greatest strength is in text and file manipulation, which is accomplished by using the regular expression (regex) library. Regexes, which are quite different from the wildcard-handling and filename-expansion capabilities of the shell (see Chapter 15), allow complicated pattern matching and replacement to be done efficiently and easily.

For example, the following line of code replaces every occurrence of the string bob or the string mary with fred in a line of text:

Without going into too many of the details, Table 27.7 explains what the preceding line says.

Table 27.7. Explanation of $string =~ s/bob|mary/fred/gi;


bob|mary /



Performs this pattern match on the text found in the variable called $string. Substitute.

Begins the text to be matched.

Matches the text bob or mary. You should remember that it is looking for the text mary, not the word mary; that is, it will also match the text mary in the word maryland.

Ends text to be matched; begins text to replace it. Replaces anything that was matched with the text fred. Ends replace text.

Does this substitution globally; that is, replaces the match text wherever in the string you match it (and any number of times).

The search text is not case sensitive. It matches bob, Bob, or bOB.

Indicates the end of the line of code.

If you are interested in the details, you can get more information using the regex (7) section of the manual.

Although replacing one string with another might seem a rather trivial task, the code required to do the same thing in another language (for example, C) is rather daunting unless supported by additional subroutines from external libraries.



Was this article helpful?

0 0

Post a comment