Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A question about groups in regular expressions

Status
Not open for further replies.

moroshko

Programmer
Joined
May 24, 2008
Messages
14
Location
IL
Can someone tell me please why in the following program $1 is not defined ? I thought that every group (every pair of parentheses) is going to $1, $2, $3 and so on.
Where am I wrong ?
Which pairs of parentheses are going to $1, $2, $3, ... ?
Thanks in advance !!


$_ = "a bc";

if (/(bc)?/) {
print "\$1 = [$1]\n" if (defined $1);
} else {
print "No match !";
};
 
The problem in your example appears to be the quantifier "?". I am not sure why that is a problem though. If you do this:

Code:
$_ = "a bc";

if (/(bc)/) {
   print "\$1 = [$1]\n" if (defined $1);
} else {
   print "No match !";
};

$1 gets defined. If you do this:

Code:
$_ = "a bc";

if (/(bc)?/) {
   print "Matched 1\n";
   print "\$1 = [$1]\n" if (defined $1);
} else {
   print "No match !";
};

"Matched !" is printed but $1 is not defined. The quantifier is interfering with the pattern memory but not the matching. Maybe someone else can explain why.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top