Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables that contain special characters in Perl regexes

I'm trying to search an array for lines that contain $inbucket[0]. Some of my $inbucket[0] values include special characters. This script does exactly what I want it to, until I hit a special character.

I want the query to be case insensitive, match any part of the string $var, and process the 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);
        }
    }
}
like image 872
McLuvin Avatar asked Dec 28 '22 19:12

McLuvin


1 Answers

You can use quotemeta, which returns the value of its argument with all non-"word" characters backslashed.

$lookfor2 = quotemeta $inbucket[0];

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

if ( $var =~ /\Q$lookfor2/i ) {
like image 67
FMc Avatar answered Apr 09 '23 13:04

FMc