in reply to loop/substitution problem

Put the call to your subroutine outside the loop:
$/=""; my $randstr = rvg(); while(<FILE>) { s/(?<!\\)(\$\w+(?![\[{\w]))/$randstr/g; print; }