next up previous contents
Next: Using Regular Expressions Up: Regular Expressions Previous: Regular Expressions

What are regular Expressions

You can use a regular expression to find patterns in strings: for example, to look for a specific name in a phone list or all of the names that start with the letter a. Pattern matching is one of Perl's most powerful and probably least understood features. But after you read this chapter, you'll be able to handle regular expressions almost as well as a Perl guru. With a little practice, you'll be able to do some incredibly handy things.

There are three main uses for regular expressions in Perl: matching, substitution, and translation. The matching operation uses the m// operator, which evaluates to a true or false value. The substitution operation substitutes one expression for another; it uses the s// operator. The translation operation translates one set of characters to another and uses the tr// operator.

All three regular expression operators work with $_ as the string to search. You can use the binding operators (see later in this section) to search a variable other than $_.

Both the matching (m//) and the substitution (s///) operators perform variable interpolation on the PATTERN and REPLACEMENT strings. This comes in handy if you need to read the pattern from the keyboard or a file.

If the match pattern evaluates to the empty string, the last valid pattern is used. So, if you see a statement like print if //; in a Perl program, look for the previous regular expression operator to see what the pattern really is. The substitution operator also uses this interpretation of the empty pattern.


next up previous contents
Next: Using Regular Expressions Up: Regular Expressions Previous: Regular Expressions
dave@cs.cf.ac.uk