Click to See Complete Forum and Search --> : Ignoring metacharacters in string variables


PatrickInDenmar
01-02-2009, 11:49 AM
Hi Iam trying to do a substitution with string variables:
$line =~ s:$source:$target: ;

$source and $target are read from a line in a file. One line I have been using is:
+-MENU ==> %
this line is processed by splitting over ==> and removing white space. This leaves $source to be +-MENU. Howver the + sign is being treated as a metacharacter, not as a string literally.

So how can I further process $source so that the Perl interpreter will treat the string without interpretation ?

Sixtease
01-03-2009, 01:50 AM
Use the \Q sequence, which escapes every non-literal by adding backslashes:
$line =~ s:\Q$source:$target: ;
However, beware of UTF-8. If your $source string contains multibyte characters, this won't work as it treats the string as a sequence of octets (shame on perl for this!).

If $source contains any multibyte characters, you'll have to add the backslashes yourself:
$source =~ s/(\W)/\\$1/g;
$line =~ s:$source:$target: ;
I've not tested it but think it should work. Hope this helps.

PatrickInDenmar
01-03-2009, 04:52 AM
Thanks SixTease, that works (and No I am not using multi-byte characters, just Plain Old Ascii). There is always a way in Perl; it's just that the books dont always tell you - Patrick

Sixtease
01-03-2009, 05:40 AM
One of the things I find so adorable about Perl is that the official documentation (http://perldoc.perl.org/perlreref.html#ESCAPE-SEQUENCES) is so great and fun to read. No books needed. (But Perl Best Practices by Damian Conway is great nonetheless.)