How can I escape meta-characters when I interpolate a variable in Perl's match operator?

Paul Nathan picture Paul Nathan · Jan 4, 2010 · Viewed 17.6k times · Source

Suppose I have a file containing lines I'm trying to match against:

foo
quux
bar

In my code, I have another array:

foo
baz
quux

Let's say we iterate through the file, calling each element $word, and the internal list we are checking against, @arr.

if( grep {$_ =~ m/^$word$/i} @arr)

This works correctly, but in the somewhat possible case where we have an test case of fo. in the file, the . operates as a wildcard operator in the regex, and fo. then matches foo, which is not acceptable.

This is of course because Perl is interpolating the variable into a regex.

The question:

How do I force Perl to use the variable literally?

Answer

Ivan Nevostruev picture Ivan Nevostruev · Jan 4, 2010

Use \Q...\E to escape special symbols directly in perl string after variable value interpolation:

if( grep {$_ =~ m/^\Q$word\E$/i} @arr)