I have a substitution that expands variables and it appears many times in my code. It looks like this:

  $link =~ s/((?:\$\w+)(?:->\{\w+\})?)/$1/eeg; # Expand variables. UNSAFE!

I recently modified the regex so I could expand syntax like $foo->{bar} but when I did that I then had to modify every single copy. I think it would be cleaner if I deduplicate it, but I'm not sure of the best way.

I can't easily stick it in a function because the variables that are being expanded are not visible in the function. I think it might be possible if I prefix all of them local, but that seems like it might create unintended problems.

Also, afaict I can't create some sort of a pseudo precompiled substitution because of the same restrictions (ie to-be-expanded variables not visible in function).

So for right now I've precompiled just the regex:

my $VAR_CAPTURE = qr/((?:\$\w+)(?:->\{\w+\})?)/;
...
  $foo =~ s/$VAR_CAPTURE/$1/eeg;
...
  $bar =~ s/$VAR_CAPTURE/$1/eeg;
...
etc etc

Is there a better way to do this, or one that is more easily understood?

For example I think something like this would look a lot better:

expand_variables_UNSAFE($foo);

In reply to Deduplicating a substitution that expands variables by raysatiro

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.