It's a closure problem (which I don't understand well). The fix looks like:

sub domatch { my ($str, $regex) = @_; our %mv; # Note the our return 0 if $str !~ /$regex/; return \%mv if keys %mv != 0; print "No keys in hash.\n"; return 0; }

Which in the context of your sample code prints:

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

Neat trick with the (?{...$^N}) BTW.


DWIM is Perl's answer to Gödel

In reply to Re: regex eval capture weirdness by GrandFather
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.