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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.