Book HomeLearning Perl, 3rd EditionSearch this book

7.3. A Pattern Test Program

When in the course of Perl events it becomes necessary for a programmer to write a regular expression, it may be difficult to tell just what the pattern will do. It's normal to find that a pattern matches more than you expected, or less. Or it may match earlier in the string than you expected, or later, or not at all.

This program is useful to test out a pattern on some strings and see just what it matches, and where:

#!/usr/bin/perl
while (<>) {                        # take one input line at a time
  chomp;
  if (/YOUR_PATTERN_GOES_HERE/) {
    print "Matched: |$`<$&>$'|\n";  # Mystery code! See the text.
  } else {
    print "No match.\n";
  }
}

This pattern test program is written for programmers to use, not endusers; you can tell because it doesn't have any prompts or usage information. It will take any number of input lines and check each one against the pattern that you'll put in place of the string saying YOUR_PATTERN_GOES_HERE. For each line that matches, the line with "mystery code" will be run. We'll learn about what that line is really doing in Chapter 9, "Using Regular Expressions". But what you'll see is this: if the pattern is /match/ and the input is beforematchafter, the output will say "|before<match>after|", using angle brackets to show you just what part of the string was matched by your pattern. Try it and see! If you pattern matches something you didn't expect, you'll be able to see that right away.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.