Basilides has asked for the wisdom of the Perl Monks concerning the following question:

More woe: apologies in advance. I'm working with a text file which represents a foreign language with accents by putting slashes (acute accent), backslashes (grave), and parentheses (aspirants) after the vowel they should sit on top of. This is cool because it means you can properly represent a language in an ASCII format. However, it's giving me hell in regexes.

Take the word "ai(=ma" (haema-, blood). I'd like to use a regex to match the stem, "ai(=m-", to, say, the genitive singular,
"ai(=matos". Should be simple:

if ($word =~ m/^$stem/) {blah;}
but everything keeps bumming out because of the special keys, which I don't want to be read as special keys (except the caret at the start). How can I keep my caret, and then have all /, \, ( and ) characters taken at face value?

Replies are listed 'Best First'.
Re: Escaping in regexes
by kvale (Monsignor) on Jun 28, 2002 at 00:02 UTC
    If you want to escape any troublesome metacharacters, use the  \Q...\E quotes:
    if ($word =~ m/^\Q$stem\E/) {blah;}

    -Mark
Re: Escaping in regexes
by Hofmator (Curate) on Jun 28, 2002 at 10:16 UTC
    just for the sake of completeness ... quotemeta
    $stem = quotemeta $stem; if ($word =~ m/^$stem/) {blah;}

    -- Hofmator