25.7. Regular Expressions
One technology that Perl is renowned for is regular expressions (commonly abbreviated regex). Regular expressions are special strings used as a template to match content, a kind of search expression in a way. Regular expressions are used in one of three ways: to match, to substitute, and to translate. Using regular expressions, you can construct advanced pattern-matching algorithms. The following sections cover the basics of Perl regular expressions.
Coverage of regular expressions can fill a book in itself. This section serves only as an introduction to the subject.
25.7.1. Regular Expression Operations
Regular expressions have three main operations in Perl: matching, substitution, and translation. In Perl you delimit regular expressions with forward slashes, prefixing the expression with the operator. An example of each operator's syntax is shown in the following code:
m/<expression>/ # match expression s/<expression1>/<expression2>/ # substitute expression2 for expression1 tr/<expression>/ # translate expression
By default, Perl uses the built-in variable $_ as the space to be searched/matched by a regular expression and the variables $n ($1, $2, and so on) as variables to store data returned from regular expression operations. You can also use the regex assignment operator (=~) to perform a regex operation on any variable's content. For example, to perform a regex operation on the text stored in the string variable $content, you could use the following ...