I've got a rather... bizarre problem involving regex embedded code. I have a program that finds files, and matches them to different rules, which do various things to the files. The regexes are specified with a simple syntax and expanded into full-blown regexes later. The regex is designed to not only match the filenames, but also to store important parts of the string for later (for use in constructing an output filename, for example). Here's the important bit of code:
#!/usr/bin/perl -w use strict; use re 'eval'; my @strings = ('test_001022','test_585381','test_389742','test_330104' +); my $capture = 'test_%a%b'; my %matchers = ('a' => '(\d{2})(?{ $mv{a} = $^N })', 'b' => '(\d{4})(?{ $mv{b} = $^N })' ); sub addmatchers { my ($regex) = @_; $regex =~ s/%(.)/$matchers{$1}/g; return $regex; } sub domatch { my ($str, $regex) = @_; my %mv; if ($str =~ /$regex/) { if (keys %mv == 0) { print "No keys in hash.\n"; return 0; } else { return \%mv; } } else { return 0; } } print "original pseudo-regex: $capture\n"; my $r = addmatchers($capture); print "modified regex: $r\n\n"; foreach my $str (@strings) { print "Matching on $str\n"; my $result = domatch($str,$r); if ($result) { print "Result:\n"; foreach my $k (keys %{$result}) { print "\t$k => $result->{$k}\n"; } } else { print "No match.\n"; } }
The addmatchers() function turns $capture into a regex by substituting in specialized matchers that match a bit of text and store it in a hash. This regex is then run with domatch(), matches are stored in the local %mv hash, and the resulting hash is returned if the regex matches.
The problem is that only the first match seems to work. For subsequent strings, the regex matches successfully, but the hash comes back empty. Here's an example run:
original pseudo-regex: test_%a%b modified regex: test_(\d{2})(?{ $mv{a} = $^N })(\d{4})(?{ $mv{b} = $^N + }) Matching on test_001022 Result: a => 00 b => 1022 Matching on test_585381 No keys in hash. No match. Matching on test_389742 No keys in hash. No match. Matching on test_330104 No keys in hash. No match.
My first thought was "I've found a bug in perl!", but now I think there's some bizarre regex backtrack scoping... thing... going on. I've tried this with Perl versions 5.8.4 (Slackware 10.0), 5.8.6 (Fedora Core 4), and 5.8.7 (Debian unstable) with identical results.
In reply to regex eval capture weirdness by bytex64
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |