Mike Gossland's Perl Tutorial Course for Windows

Introduction | Binding Op | Reg Expressions | Examples | Substitution | Advanced

Chapter 2: Matching and Substitution

The Binding Operator

When you do a pattern match, you need three things:

  • the text you are searching through
  • the pattern you are looking for
  • a way of linking the pattern with the searched text

As a simple example, let's say you want to see whether a string variable has the value of "success". Here's how you could write the problem in Perl:

$word = "success";

if ( $word =~ m/success/ ) {
print "Found success\n";
} else {
print "Did not find success\n";

There are two things to note here.

First, the "=~" construct, called the binding operator, is what binds the string being searched with the pattern that specifies the search. The binding operator links these two together and causes the search to take place.

Next, the "m/success/" construct is the matching operator, m//, in action. The "m" stands for matching to make it easy to remember. The slash characters here are the "delimiters". They surround the specified pattern. In m/success/, the matching operator is looking for a match of the letter sequence: success.

Generally, the value of the matching statement returns 1 if there was a match, and 0  if there wasn't. In this example, the pattern matches so the returned value is 1, which is a true value for the if statement, so the string "Found success\n" is printed.