Greetings,
Just some updates to your code. I declared %mv in the main scope as "our" so it can be localized in your &domatch() sub later on. The code below works fine for me.
#!/usr/bin/perl -w use strict; use re 'eval'; my @strings = ('test_001022','test_585381','test_389742','test_330104' +); my $capture = 'test_%a%b'; #added our to your %mv declaration so it can be localized in &domatch( +); our %mv; 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) = @_; #localize %mv local %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. ($r)\n"; } }

Here is the output I get
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 Result: a => 58 b => 5381 Matching on test_389742 Result: a => 38 b => 9742 Matching on test_330104 Result: a => 33 b => 0104


-InjunJoel
"I do not feel obliged to believe that the same God who endowed us with sense, reason and intellect has intended us to forego their use." -Galileo

In reply to Re: regex eval capture weirdness by injunjoel
in thread regex eval capture weirdness by bytex64

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.