in reply to How do I avoid double substitution when replacing many patterns?
Why not just combine the two into one regexp, skirting the issue entirely?
$phrase = '$foo $(bar)'; $variables = { foo => '$(bar)', bar => '$(foo)' }; $phrase =~ s/ (?: # Just take the first one \$([a-zA-Z0-9_]+) ) | # And alternate it with the second (?: \$\(([a-zA-Z0-9_]+)\) ) /$variables->{$1||$2}/xg; # Then do the substitution for the one # that matched print $phrase; # Prints "$(bar) $(foo)"
I'm sure there's an easier and more efficient way to write this regex, but this seems like the straightforward solution. You eliminate the second pass, so you eliminate the double interpolation. This particular scheme fails if you allow a variable named '0' though, so you may need to do something else in the replacement part if this is the case.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: How do I avoid double substitution when replacing many patterns?
by diotalevi (Canon) on Jan 20, 2007 at 18:04 UTC | |
by japhy (Canon) on Jan 20, 2007 at 18:18 UTC | |
by diotalevi (Canon) on Jan 20, 2007 at 19:02 UTC | |
Re^2: How do I avoid double substitution when replacing many patterns?
by bart (Canon) on Jan 21, 2007 at 07:51 UTC | |
by diotalevi (Canon) on Jan 21, 2007 at 20:14 UTC | |
Re^2: How do I avoid double substitution when replacing many patterns?
by kyle (Abbot) on Jan 20, 2007 at 19:13 UTC |