Home > Articles > Web Development > Perl

Regular Expressions in Perl—Pattern Matching

  • Print
  • + Share This
If you are familiar with UNIX utilities, such as vi, sed, grep, and awk, you have met face-to-face with the infamous regular expressions and metacharacters used in delimiting search patterns. Well, with Perl, they're back! Learn what they are and how to use them.
This chapter is from the book

This chapter is from the book

8.1 What Is a Regular Expression?

If you are familiar with UNIX utilities, such as vi, sed, grep, and awk, you have met face-to-face with the infamous regular expressions and metacharacters used in delimiting search patterns. Well, with Perl, they're back!

What is a regular expression, anyway? A regular expression is really just a sequence, or pattern, of characters that is matched against a string of text when performing searches and replacements. A simple regular expression consists of a character or set of characters that matches itself. The regular expression is normally delimited by forward slashes.1 The special scalar $_ is the default search space where Perl does its pattern matching. $_ is like a shadow. Sometimes you see it; sometimes you don't. Don't worry; all this will become clear as you read through this chapter.

Example 8.1.

1   /abc/
2   ?abc?

Explanation

  1. The pattern abc is enclosed in forward slashes. If searching for this pattern, for example, in a string or text file, any string that contained the pattern abc would be matched.
  2. The pattern abc is enclosed in question marks. If searching for this pattern, only the first occurrence of the string is matched. (See the reset function in Appendix A.)
  • + Share This
  • 🔖 Save To Your Account