next up previous contents
Next: The Matching Options Up: Regular Expressions Previous: Substitution

The Matching Operator (m//)

The matching operator (m//) is used to find patterns in strings. One of its more common uses is to look for a specific string inside a data file. For instance, you might look for all customers whose last name is "Johnson," or you might need a list of all names starting with the letter s.

The matching operator only searches the $_ variable. This makes the match statement shorter because you don't need to specify where to search. Here is a quick example:

$_ = "AAA bbb AAA";
print "Found bbb\n" if  m/bbb/;

The print statement is executed only if the bbb character sequence is found in the $_ variable. In this particular case, bbb will be found, so the program will display the following:

Found bbb

The matching operator allows you to use variable interpolation in order to create the pattern. For example (match1.pl):

$needToFind = "bbb";
$_ = "AAA bbb AAA";
print "Found bbb\n" if  m/$needToFind/;

Using the matching operator is so commonplace that Perl allows you to leave off the m from the matching operator as long as slashes are used as delimiters (match2.pl):

$_ = "AAA bbb AAA";
print "Found bbb\n" if  /bbb/;

Using the matching operator to find a string inside a file is very easy because the defaults are designed to facilitate this activity. For example ( match3.pl):

$target = "M";
open(INPUT, "<findstr.dat");
while (<INPUT>) {
     if (/$target/) {
         print "Found $target on line $.";
     }
}
close(INPUT);

Note The $. special variable keeps track of the record number. Every time the diamond operators read a line, this variable is incremented.

This example reads every line in an input searching for the letter M. When an M is found, the print statement is executed. The print statement prints the letter that is found and the line number it was found on.



 
next up previous contents
Next: The Matching Options Up: Regular Expressions Previous: Substitution
dave@cs.cf.ac.uk