Perl Operators   «Prev  Next»
Lesson 8Perl match operator
Objective Examine the strengths of the match operator.

Perl Match Operator

Perl has three different pattern-matching operators:
  1. One for matching
  2. One for substitution (search and replace)
  3. One for character translation
These operators work with regular expressions, which are covered in detail in the next module, and give you the power to search and replace within text. We will concentrate on the syntax of the operators over the next several lessons, along with just enough detail to allow you to understand their use.

Match operator

The match operator (m/pattern/) is usually written without the m, like this:
/pattern/. Just like the quote operators, you can use any characters to delimit the pattern, but you must use / characters if you want to omit the m.

# matches "foo/bar", which has a / in it
m(foo/bar)   

The pattern is a regular expression, but it can be simply the text you want to search for. Here is a simple program that prints all the lines in a file that have the word hello in them.
#!/usr/bin/perl -w

while(<>) {
   print if /hello/i;
}

Run that program with a filename (or filenames) on the command line, and it will print only the lines that have the word hello in them.

Match operator switches

Notice the i character right after the match operator. This is one of several switches that you can use. In the next lesson, we will cover the substitute operator.