www.webdeveloper.com
Results 1 to 4 of 4

Thread: Ignoring metacharacters in string variables

  1. #1
    Join Date
    Jan 2009
    Posts
    2

    Question Ignoring metacharacters in string variables

    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 ?

  2. #2
    Join Date
    Oct 2007
    Location
    Vienna, Austria
    Posts
    387
    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:
    Code:
    $source =~ s/(\W)/\\$1/g;
    $line =~ s:$source:$target: ;
    I've not tested it but think it should work. Hope this helps.

  3. #3
    Join Date
    Jan 2009
    Posts
    2

    Smile

    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

  4. #4
    Join Date
    Oct 2007
    Location
    Vienna, Austria
    Posts
    387
    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.)

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles