in reply to loop/substitution problem

Use a cache-hash.
s/(?<!\\)(\$\w+)(?![[{\w])/$rep{$1} ||= rvg()/ge;
That way, "$foo" always gets replaced by the same text.

japhy -- Perl and Regex Hacker