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 ?
Use the \Q sequence, which escapes every non-literal by adding backslashes:
Code:
$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:
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
One of the things I find so adorable about Perl is that the official documentation is so great and fun to read. No books needed. (But Perl Best Practices by Damian Conway is great nonetheless.)
Bookmarks