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);
  • Comment on Deduplicating a substitution that expands variables

Replies are listed 'Best First'.
Re: Deduplicating a substitution that expands variables
by AnomalousMonk (Archbishop) on Mar 03, 2017 at 09:52 UTC
    Is there a better way to do this, or one that is more easily understood?

    A better and more easily understood (and maintained) way would probably be with a templating module as AnonyMonk has suggested. If you're willing to put all the translation strings into a single hash and pass it around by reference (and you're into masochism), maybe something like:

    c:\@Work\Perl\monks>perl -wMstrict -le "my %Xlate = ( foo => { qw(one UNO two DOS) }, bar => { qw(fee fie zit zot) }, quux => 'hi there', ); ;; sub expand { my ($str, $hr_xlt) = @_; ;; my $k = qr{ \w+ }xms; my $v = qr{ -> [{] \w+ [}] }xms; ;; $str =~ s{ (\$) ($k) ($v?) }{ qq{\$hr_xlt->{$2}$3} }xmseeg; return $str; } ;; my $s = 't$foo->{one}u $bar->{zit} v $quux w'; print qq{'$s'}; ;; $s = expand($s, \%Xlate); print qq{'$s'}; " 't$foo->{one}u $bar->{zit} v $quux w' 'tUNOu zot v hi there w'
    (Note this doesn't work if the string is '$quuxw'; more delimitation needed.)


    Give a man a fish:  <%-{-{-{-<

Re: Deduplicating a substitution that expands variables (template)
by Anonymous Monk on Mar 03, 2017 at 07:39 UTC