in reply to unescape a user-entered string?

Here's some code I've been using to both escape and unescape strings. One of its good points is its extensible nature. Now it escapes/unescapes newlines as '\n', tabs as '\t' and backslashes as double backslashes. You shouldn't forget about those, how else would you want to allow a user to enter any text they like, like a backslash followed by an 'n'?

I would believe that by mere inspection of the code, it is clear how to extend it.

BEGIN { use Regex::PreSuf; my %escape = ( "\n" => '\\n', "\t" => '\\t', "\\" => '\\\\'); my $escape = presuf(keys %escape); my %unescape = reverse %escape; my $unescape = presuf(keys %unescape); sub escape { local $_ = shift; s/($escape)/$escape{$1}/go; $_; } sub unescape { local $_ = shift; s/($unescape)/$unescape{$1}/go; $_; } }
The BEGIN block is only desirable if you just paste this code into your script. The idea is that the hash and regex will be properly initialised at the time you try to actually use it one of these functions.

I do have some doubts on the choice of function names, though. They're not actually saying much.

p.s. You do need the latest patched version for Regex::PreSuf, as the previous version couldn't properly handle strings with embedded newlines.