s/\\n/\n/g;

You've broken the solution by creating it: I might have had a plaintext \n in the text before, that now becomes a newline. Oops.

If you escape any characters, you need to escape the escape character as well:

s/\\/\\s/g; s/\n/\\n/g; s/\r/\\r/g;
so that a plaintext \n becomes \sn, which won't be matched by the regex that unescapes newlines. Then you can do the same thing backwards:
s/\\n/\n/g; s/\\r/\r/g; s/\\s/\\/g;
Just don't forget to leave the last unescaping last. If the escape code for the character is itself (ie s/\\/\\\\/g;), then unescaping becomes much more complicated, because you could match a \n that's actually part of a sequence like \\n. So you'll have to unwrap the string very carefully:
my %xlat = ('\\' => "\\", 'n' => "\n", 'r' => "\r"); s/\G(?:\\(.)|(.))/defined($1) ? $xlat{$1} : $2/eg;

And I haven't tested this, so I'm not even sure I got it right on the first try.

Quoting and escaping are hair-raisingly complex issues - be careful.

I have discovered that there are two types of command interfaces in the world of computing:
good interfaces and user interfaces.

— Dan J. Bernstein, The qmail security guarantee

Makeshifts last the longest.


In reply to Re^2: changing data in a file (pitfalls of proper quoting) by Aristotle
in thread changing data in a file by simonthom

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.