Ew. That that sprinkles eval blocks all over. That's also suboptimal. The original poster had the best version already. I fixed my own code to be nearly similar except that it doesn't benefit from perl's ability to compile a static regex only once. Your code is a static regex but you're imposing eval {} at each match point. An entirely different route might be to do some code generation so that the common parts are written only once, eval blocks aren't sprinked all over the place and the world is good again. The only issue is that now its not pretty anymore.
# Keep $escape somewhere or give it a proper name.
my $escape = eval "sub {\n".join("\n",map " \$_[0] =~ s/\\$_/\\\\$_
+/g;", qw/t r n f/)."\n};";
$escape->( $text );
|