Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 794
Paul Nathan Avatar asked Jan 04 '10 18:01

Paul Nathan


People also ask

How do I escape a regular expression in Perl?

Because backslash \ has special meaning in strings and regexes, if we would like to tell Perl that we really mean a backs-slash, we will have to "escape" it, by using the "escape character" which happens to be back-slash itself. So we need to write two back-slashes: \\.

What is * in Perl regex?

Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“.

What does =~ do in Perl?

The operator =~ associates the string with the regex match and produces a true value if the regex matched, or false if the regex did not match. In our case, World matches the second word in "Hello World" , so the expression is true.


1 Answers

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

if( grep {$_ =~ m/^\Q$word\E$/i} @arr)
like image 164
Ivan Nevostruev Avatar answered Oct 13 '22 02:10

Ivan Nevostruev