Interpolation - Page 4
February 9, 2001
Regular expressions work a little like double-quoted strings;
variables and metacharacters are interpolated. This allows us to
store patterns in variables and determine what we are matching
when we run the program - we don't need to have them hard-coded
in:
Try it out - Pattern Tester
This program will ask the user for a pattern and then test to see
if it matches our string. We can use this throughout the chapter
to help us test the various different styles of pattern we'll be
looking at:
#!/usr/bin/perl
# matchtest.plx
use warnings;
use strict;
$_ = q("I wonder what the Entish is for 'yes'
and 'no'," he thought.);
# Tolkien, Lord of the Rings
print "Enter some text to find: ";
my $pattern = <STDIN>;
chomp($pattern);
if (/$pattern/) {
print "The text matches the pattern '$pattern'.\n";
} else {
print "'$pattern' was not found.\n";
}
[Lines 5 and 6 above are one line. They have been split for formatting purposes.]
Now we can test out a few things:
> perl matchtest.plx
Enter some text to find: wonder
The text matches the pattern 'wonder'.
> perl matchtest.plx
Enter some text to find: entish
'entish' was not found.
> perl matchtest.plx
Enter some text to find: hough
The text matches the pattern 'hough'.
> perl matchtest.plx
Enter some text to find: and 'no',
The text matches the pattern 'and 'no''.
Pretty straightforward, and I'm sure you could all spot those not
in $_ as well.
How It Works
matchtest.plx has its basis in the three lines:
my $pattern = <STDIN>;chomp($pattern);
if (/$pattern/) {
We're taking a line of text from the user. Then, since it will
end in a new line, and we don't necessarily want to find a new
line in our pattern, we chomp it away. Now we do our
test.
Since we're not using the =~ operator, the test will
be looking at the variable $_. The regular
expression is /$pattern/, and just like the double-
quoted string "$pattern", the variable
$pattern is interpolated. Hence, the regular
expression is purely and simply whatever the user typed in, once
we've got rid of the new line.
Check back in two weeks for Part 2!
Checking the Syntax - Page 3
Beginning Perl
|