in reply to Escape special characters for a LaTeX file
BrowserUk's approach to your escaping problem is, of course, the way to go. However, in the hope that you may be spared some future headaches, a couple of features of the OPed code other than those already noted deserve comment.
my @special_characters = q{# $ % & ~ _ \\ { } ^};
This statement assigns a single element that is a string to an array (which it also creates).
See perlintro, List value constructors in perldata.c:\@Work\Perl>perl -wMstrict -MData::Dump -le "my @special_characters = q{# $ % & ~ _ \\ { } ^}; dd \@special_characters; print 'number of elements in array: ', scalar @special_characters; " ["# \$ % & ~ _ \\ { } ^"] number of elements in array: 1
foreach my $i (@special_characters) {
$text =~ s/$special_characters[$i]/\\$&/g;
}
This loops over the single element of the array, a string that is not numeric (i.e., doesn't "look like" a number; by default, Perl evaluates such a string to 0), and then uses the string as an index into the array. This should have produced a nice, fat warning.
c:\@Work\Perl>perl -wMstrict -le "my @special_characters = q{# $ % & ~ _ \\ { } ^}; ;; foreach my $i (@special_characters) { print qq{>>$special_characters[$i]<<}; } " Argument "# $ % & ~ _ \\ { } ^" isn't numeric in array element at -e l +ine 1. >># $ % & ~ _ \ { } ^<<
|
|---|