Using Variables Containing Special Characters in Perl Regular Expressions

I am trying to find an array for strings containing $ inbucket [0]. Some of my $ inbucket [0] values ​​include special characters. This script does exactly what I want until I hit a special character.

I want the query to be case insensitive, match any part of the $ var string, and process special characters literally, as if they weren't special. Any ideas?

Thanks!

sub loopthru() { warn "Loopthru begun on $inbucket[0]\n"; foreach $c (@chat) { $var = $c->msg; $lookfor2 = $inbucket[0]; if ( $var =~ /$lookfor2/i ) { ($to,$from) = split('-',$var); $from =~ s/\.$//; print MYFILE "$to\t$from\n"; &fillbucket($to); &fillbucket($from); } } } 
+4
source share
2 answers

You can use quotemeta , which returns the value of its argument with all characters without a word.

 $lookfor2 = quotemeta $inbucket[0]; 

Or you can use escape \Q , which is mentioned in perlre . In short, it will quote (disable) the template metacharacters until \E encountered.

 if ( $var =~ /\Q$lookfor2/i ) { 
+8
source

I think you are looking for $var =~ /\Q$lookfor2/i

perl faq

+2
source

All Articles