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 12, “Automating Tasks and Shell Scripting”), 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:

$string =~ s/bob|mary/fred/gi;

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

TABLE 40.7 Explanation of $string =~ s/bob|mary/fred/gi;

Get Ubuntu Unleashed 2014 Edition: Covering 13.10 and 14.04,Ninth 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.