cfreak has asked for the wisdom of the Perl Monks concerning the following question:
Earlier today I ran across a small problem with a script of mine. I never realized that a parenthetical capture does not reset the $1 ... $n variables, nor does it reset $&. Here's a test case
#!/usr/bin/perl use strict; my $count = 0; while(<DATA>) { $_ =~ /(foo)/; if($1) { print "$count: $1 -- $&\n"; $count ++; } } exit; __DATA__ foo bar baz foobar fjkdlsa jewklf fdlkjsa jfj49i fjdals; foo fjkdsla
When run this outputs:
0: foo -- foo 1: foo -- foo 2: foo -- foo 3: foo -- foo 4: foo -- foo 5: foo -- foo 6: foo -- foo 7: foo -- foo 8: foo -- foo 9: foo -- foo 10: foo -- foo
Not exactly what I was looking for.
So my question is, is this a feature or a bug? Also I didn't find anything in perlre that really warned of this gotcha, if its a feature: my suggestion is that it should be better documented (if it is please show me where! :) )
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
•Re: Regex variable capturing gotcha
by merlyn (Sage) on Aug 04, 2004 at 18:17 UTC | |
|
Re: Regex variable capturing gotcha
by Aristotle (Chancellor) on Aug 04, 2004 at 18:21 UTC | |
by Anonymous Monk on Aug 05, 2004 at 00:31 UTC | |
|
Re: Regex variable capturing gotcha
by ccn (Vicar) on Aug 04, 2004 at 18:20 UTC |