I am reading the book "Beginning Perl" by James Lee and have been pretty happy with the content so far. That said I am stuck on chpt 7 which deals with regular expressions - I can't get the backreferences to work even when I copy the source verbatim.

source:

#!/usr/bin/perl -w
# matchtest2.pl
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);

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";
}

Printing the $& variable displays 409 with expression \b\w{3}\b, but the $1 variable shows nothing.
I'm using perl, v5.10.0 built for i486-linux-gnu-thread-multi

Is this syntax outdated or obsolete?
Any and all help is appreciated.

What are you entering into $pattern?

Multiple patterns:

jondev:/home/jondev/begperl/chp7> matchtest1.pl
Enter a regular expression: \b\w{3}\b
\b\w{3}\b found in 1: A silly sentence (495,a) *BUT* one which will be useful. (3)
$& = 495
jondev:/home/jondev/begperl/chp7>
>>>
jondev:/home/jondev/begperl/chp7> matchtest1.pl
Enter a regular expression: s\w+
s\w+ found in 1: A silly sentence (495,a) *BUT* one which will be useful. (3)
$& = silly
jondev:/home/jondev/begperl/chp7>
>>>
jondev:/home/jondev/begperl/chp7> matchtest1.pl
Enter a regular expression: [^0-9 ^A-Z]\w+
[^0-9 ^A-Z]\w+ found in 1: A silly sentence (495,a) *BUT* one which will be useful. (3)
$& = silly
jondev:/home/jondev/begperl/chp7>
>>>
jondev:/home/jondev/begperl/chp7> matchtest1.pl
Enter a regular expression: [^0-9 ^A-Z ^a-z]\w+
[^0-9 ^A-Z ^a-z]\w+ found in 1: A silly sentence (495,a) *BUT* one which will be useful. (3)
$& = (495
jondev:/home/jondev/begperl/chp7>
>>>

#!/usr/bin/perl -w
#matchtest1.pl
use strict;

my($pattern);
$_ = '1: A silly sentence (495,a) *BUT* one which will be useful. (3)';

print "Enter a regular expression: ";
chomp($pattern = <STDIN>);

if (/$pattern/){
print "$pattern found in $_\n";
print "\$& = $&\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 NOT found\n";
}

You need parentheses for back references to capture patterns they find.


if (/($pattern)/) {

Thanks KevinADC!
didn't see any reference in the book to this issue but now works like a champ!

This question has already been answered. Start a new discussion instead.