I am attempting to use a Path::Iterator::Rule "Custom rule subroutine".

I have a regexp during the buildup of my rules, which determines whether the custom rule subroutine is used. If it indicates to use the subroutine, then its capture group $1 at this point holds some text that I want to match in the subroutine to filter for certain pathnames.

With the naive approach, it seems that the $1 or $var variable in my regexp is only expanded at the time of the regexp/subroutine being run. At this point, the variable is no longer valid and could have been overwritten by some other value. Naive code:

my $rule = Path::Iterator::Rule->new; if ($id =~ /^([0-9A-F]{2})/) { my $int = $1; $rule->and( sub { m#/INT $int# } ); }

Resulting errors are many times this line:

Use of uninitialized value $int in regexp compilation at [redacted]/proj/intlist/intlist.pl line 1167.

I found that it appears to work if I use a "postponed" regular subexpression like so:

my $rule = Path::Iterator::Rule->new; if ($id =~ /^([0-9A-F]{2})/) { my $int = $1; $rule->and( sub { m#/INT (??{ "$int" })# } ); }

Is this a correct approach? Are there other ways to interpolate a variable at the time of adding the custom rule subroutine, so that the rule doesn't refer to the variable later but rather uses the text that it used to hold?


In reply to Interpolate variable into regexp at time of definition rather than execution, as a filter for Path::Iterator::Rule by ecm

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.