Try It Out - Page 11
March 9, 2001
First, though, let's rewrite our test program so that we can see
what's in those variables:
Try it out : A Second Pattern Tester
#!/usr/bin/perl
# matchtest2.plx
use warnings;
use strict;
$_ = '1: A silly sentence (495,a)
*BUT* one which will be useful. (3)';
print "Enter a regular expression: ";
my $pattern = <STDIN>;
chomp($pattern);
[Lines 5 and 6 above are one line. They have been split for
formatting purposes.]
if (/$pattern/) {
print "The text matches the pattern '$pattern'.\n";
print "\$1 is '$1'\n" if defined $1;
print "\$2 is '$2'\n" if defined $2;
print "\$3 is '$3'\n" if defined $3;
print "\$4 is '$4'\n" if defined $4;
print "\$5 is '$5'\n" if defined $5;
} else {
print "'$pattern' was not found.\n";
}
Note that we use a backslash to escape the first 'dollar' symbol
in each print statement, thus displaying the actual
symbol, while leaving the second in each to display the contents
of the appropriate variable.
We've got our special variables in place, and we've got a new
sentence to do our matching on. Let's see what's been happening:
> perl matchtest2.plx
Enter a regular expression: ([a-z]+)
The text matches the pattern '([a-z]+)'.
$1 is 'silly'
> perl matchtest2.plx
Enter a regular expression: (\w+)
The text matches the pattern '(\w+)'.
$1 is '1'
> perl matchtest2.plx
Enter a regular expression: ([a-z]+)(.*)([a-z]+)
The text matches the pattern '([a-z]+)(.*)([a-z]+)'.
$1 is 'silly'
$2 is ' sentence (495,a) *BUT* one which will be usefu'
$3 is 'l'
> perl matchtest2.plx
Enter a regular expression: e(\w|n\w+)
The text matches the pattern 'e(\w|n\w+)'.
$1 is 'n'
How It Works
By printing out what's in each of the groups, we can see exactly
what caused Perl to start and stop matching, and when. If we look
carefully at these results, we'll find that they can tell us a
great deal about how Perl handles regular expressions.
Well-Defined Repetition - Page 10
Beginning Perl
How the Engine Works - Page 12
|