pbeckingham has asked for the wisdom of the Perl Monks concerning the following question:
I have a curious piece of code, with an error in it, and while I have found the error, I can't explain the erroneous behavior. Could someone help me understand this?
I have a regex that I'm using to split apart a string, which I have simplified for this example. The regex contains capturing parentheses, and the error is that I also include capturing parentheses when I use the regex later.
#! /usr/bin/perl -w use strict; my $r = qr{(.)}; while ('abc' =~ /($r)/g) { print "loop $1\n"; } foreach ('abc' =~ /($r)/g) { print "array $_\n"; }
The output is:
loop a loop b loop c array a array a array b array b array c array c
Removing either set of capturing parentheses fixes the problem, but I don't see how the while loop doesn't also get duplicate results?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Double Capturing Parentheses
by Enlil (Parson) on Mar 22, 2004 at 03:08 UTC | |
|
Re: Double Capturing Parentheses
by bart (Canon) on Mar 22, 2004 at 08:19 UTC | |
|
Re: Double Capturing Parentheses
by eXile (Priest) on Mar 22, 2004 at 03:05 UTC |