PerlMonkJunior has asked for the wisdom of the Perl Monks concerning the following question:
I have one problem about the backreferences in regular expressions. I learned from the book "Beginning in Perl" (Page 162) that perl has a series of special variables in which it stores anything that is matched with a group in parentheses.Each time it sees a set of parentheses, it copies the matched text inside into a numbered variable- the first matched group goes in $1, the second group in $2 and so on. We call them as backreference variables.
However, when I tried out the following example in the book on my computer (the code is as follows):
########## End of the Code ####################!/usr/bin/perl use warnings; use strict; $_ = 'This is a silly sentence. {3}. 2: but one may find it useful in +learning regular expression.'; print "please enter your pattern: " my $pattern = <STDIN>; chomp($pattern); if(/$pattern/) { print "I have found the pattern: "; print "\$1 is '$1'\n" if defined $1; } else { print "Sorry, we did not find anything this time.\n"; }
When I enter a word "is" as the pattern, my program only said "I have found the pattern: ", but it did not print out the $1 it is supposed to print out. Can anyone help me out?
Thank you very much for your help in advance! Look forward to your reply soon.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Please Help: A regular expression problem
by BrimBorium (Friar) on Sep 12, 2010 at 17:57 UTC | |
|
Re: Please Help: A regular expression problem
by ww (Archbishop) on Sep 13, 2010 at 00:59 UTC | |
|
Re: Please Help: A regular expression problem
by JavaFan (Canon) on Sep 12, 2010 at 18:18 UTC | |
|
Re: Please Help: A regular expression problem
by AnomalousMonk (Archbishop) on Sep 13, 2010 at 21:22 UTC |