Very nice solution! Your interpretation of quoting is correct (I blundered before). Your solution does not work, as is, however, because $1 gets clobbered. The following minor changed version of your solution does work for me (note also the extra line of test data with your quoting example).

my $str = <<'EOS'; abc "a\"bc$xyz$abc$x$y" $bla'h, $blah hello k\$nob this is "\"'abc$xy$z\"" test "$" a$$bc "$$abc$xyz$abc$" blah, $$, blah abc "a\"bc$xy\\z$abc$x$y\\" $bla'h, "$baz" EOS print "$str\n\n"; $str =~ s[ \G # Don't skip anything ( # $1 is unquoted text (?: [^\\"]+ # Uninteresting stuff | \\. # Escaped character )* )( # $2 is quoted text " # Opening quote (?: [^\\"]+ # Unintersting stuff | \\. # Escaped character )* ("?) # $3 is closing quote ) ][ die "Unclosed quote ($2)" unless $3; my $t = $1; # changed line my $q = $2; $q =~ s[\$][\\\$]g; $t . $q; # changed line ]xseg; print $str;

which prints:

abc "a\"bc$xyz$abc$x$y" $bla'h, $blah hello k\$nob this is "\"'abc$xy$z\"" test "$" a$$bc "$$abc$xyz$abc$" blah, $$, blah abc "a\"bc$xy\\z$abc$x$y\\" $bla'h, "$baz" abc "a\"bc\$xyz\$abc\$x\$y" $bla'h, $blah hello k\$nob this is "\"'abc\$xy\$z\"" test "\$" a$$bc "\$\$abc\$xyz\$abc\$" blah, $$, blah abc "a\"bc\$xy\\z\$abc\$x\$y\\" $bla'h, "\$baz"

as does my original attempt; however, the last line of this new test data trips up the earlier one liner.


In reply to Re: Re^2: Escape $ inside quotes only (\\) by eyepopslikeamosquito
in thread Escape $ inside quotes only by eyepopslikeamosquito

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.