raysatiro has asked for the wisdom of the Perl Monks concerning the following question:
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);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Deduplicating a substitution that expands variables
by AnomalousMonk (Archbishop) on Mar 03, 2017 at 09:52 UTC | |
|
Re: Deduplicating a substitution that expands variables (template)
by Anonymous Monk on Mar 03, 2017 at 07:39 UTC |