in reply to Re^2: Escape special characters for a LaTeX file
in thread Escape special characters for a LaTeX file

Thank you again!

funny enough, I have had already tried the suggestion of BrowserUK in my script, commented out.
Now I put it back:

$text =~ s![#$%&~_}{^]!\\$&!g;

But only one character is not escaped: "%"
strange!

Replies are listed 'Best First'.
Re^4: Escape special characters for a LaTeX file
by AnomalousMonk (Archbishop) on Dec 14, 2014 at 16:04 UTC
    $text =~ s![#$%&~_}{^]!\\$&!g;

    But only one character is not escaped: "%"

    The sequence  $% is interpreted as the Perl special variable  $% (see perlvar) and its current value is interpolated. Try  [#\$%&~_}{^] (escaping the  $ character) instead.

    Update: E.g.:

    c:\@Work\Perl\monks\marek1703>perl -wMstrict -le "my $sans_esc = qr/[#$%&~_}{^]/; print $sans_esc; ;; my $with_esc = qr/[#\$%&~_}{^]/; print $with_esc; " (?^:[#0&~_}{^]) (?^:[#\$%&~_}{^])

Re^4: Escape special characters for a LaTeX file
by Laurent_R (Canon) on Dec 14, 2014 at 17:08 UTC
    Try to use the quotemeta operator (or, equivalently, the \Q ... \E tags) on your search list. It should remove all problems of this sort.

      Another way to completely defeat scalar or array interpolation in regexes (as in strings) is by use of  ' (single-quote) delimiters for the  s/// substitution:

      c:\@Work\Perl\monks\marek1703>perl -wMstrict -le "my $s = '-#-$-%-&-~-_-}-{-^-0-$%&~_}{^0'; print qq{'$s'}; ;; $s =~ s' (?= [#$%&~_{}^]) '\\'xmsg; print qq{'$s'}; " '-#-$-%-&-~-_-}-{-^-0-$%&~_}{^0' '-\#-\$-\%-\&-\~-\_-\}-\{-\^-0-\$\%\&\~\_\}\{\^0'
      (This applies also to  m// and  qr// operators.) See perlop.

        Interesting, I did not know that.
Re^4: Escape special characters for a LaTeX file
by marek1703 (Acolyte) on Dec 14, 2014 at 16:07 UTC

    Sorry! One strange thing is happening: I get this:
    1\0:\0\0
    all "0" are escaped.

      ... all "0" are escaped.

      That's because '0' (zero) is part of the character class: the value of  $% happens to be 0 at that point | the moment of regex compilation. Please see my update to the above.

      Update: E.g.:

      c:\@Work\Perl\monks\marek1703>perl -wMstrict -le "my $s = '-#-$-%-&-~-_-}-{-^-0-$%&~_}{^0'; print qq{'$s'}; ;; $s =~ s{ ([#\$%&~_{}^]) }{\\$1}xmsg; print qq{'$s'}; " '-#-$-%-&-~-_-}-{-^-0-$%&~_}{^0' '-\#-\$-\%-\&-\~-\_-\}-\{-\^-0-\$\%\&\~\_\}\{\^0'
      and also (no capture):
      c:\@Work\Perl\monks\marek1703>perl -wMstrict -le "my $s = '-#-$-%-&-~-_-}-{-^-0-$%&~_}{^0'; print qq{'$s'}; ;; $s =~ s{ (?= [#\$%&~_{}^]) }{\\}xmsg; print qq{'$s'}; " '-#-$-%-&-~-_-}-{-^-0-$%&~_}{^0' '-\#-\$-\%-\&-\~-\_-\}-\{-\^-0-\$\%\&\~\_\}\{\^0'