Search for brackets in perl

Writing a program in which I read a list of words / characters from one file and search for each of them in another text.

So this is something like:

while(<FILE>){ $findword = $_; for (@text){ if ($_=~ /$find/){ push(@found, $_); } } } 

However, I ran into a problem when brackets appear. This gives me this error:

 Unmatched ( in regex; marked by <-- HERE in m/( <-- HERE 

I understand this because Perl believes that ( is part of the regular expression, but how do I deal with it and make it ( searchable?

+4
source share
5 answers

You can use \Q and \E :

 if ($_ =~ /\Q$find\E/){ 

Or just use index if you are just looking for a literal match:

 if(index($_, $find) >= 0) { 
+4
source

In the general case, the backslash resets characters inside regular expressions - that is, /\(/ will match a literal (

in such situations, it is better to use the quote operator

 if ( $_ =~ /\Q$find\E/ ) { ... } 

alternatively use quotemeta

+3
source

You want to do /\Q$find\E/ instead of just /$find/ - \Q tell the parser to stop treating metacharacters as part of the regular expression until it finds \E

+2
source

I suspect you will find m/\Q$find\E/ useful - unless you want other Perl regular expression metacharacters to be interpreted as metacharacters.

+1
source

\Q with \e will avoid your special characters in the $find variable, for example:

 while(<FILE>){ $findword = $_; for (@text){ if ($_=~ /\Q$find\e/){ push(@found, $_); } } } 
0
source

All Articles