Playing around with regexes (abusing them :) on the weekend I came across the following (on Perl 5.6.1, ActiveState Build 626). Executing the same regex on the same string in a loop multiple times yields different results for the first run and the remaining runs. I'm running on Win2K, but I don't think this plays a role here. The code:
#!/usr/bin/perl use strict; use warnings; use re qw/eval /; my $pattern = q/(.)(?{ print ++$counts[0]; })^/; my $line = 'ab'; for (0..2) { my @counts = (0); print "$_: "; # $pattern .= '(?=.)'; $line =~ /$pattern/; print "; \@counts = (", join(', ', @counts), ")\n"; } print "\@main::counts = (", join(', ', @::counts), ")\n";
This prints - apart from the warning about the last line:
which means, it works the first time as expected but the next times my @counts doesn't get modified by the regex. However, inside the regex the variable seems to retain its value from execution to execution.0: 12; @counts = (2) 1: 34; @counts = (0) 2: 56; @counts = (0) @main::counts = ()
When using a package variable by changing my @counts to our @counts the program works as expected and prints:
0: 12; @counts = (2) 1: 12; @counts = (2) 2: 12; @counts = (2) @main::counts = (2)
When uncommenting the $pattern .= line (and going back to my) - effectively changing the pattern in every loop (remark: this does not effect the working of the regex!), the code also works as expected printing:
0: 12; @counts = (2) 1: 12; @counts = (2) 2: 12; @counts = (2) @main::counts = ()
My question - is this a known bug? Is it a bug at all or might I have overlooked a (well) documented feature ;-) and how does this behave in other versions of perl?
-- Hofmator
In reply to Perl Bug in Regex Code Block? by Hofmator
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |