McLuvin
McLuvin

Reputation: 125

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);
        }
    }
}

Upvotes: 4

Views: 9208

Answers (2)

FMc
FMc

Reputation: 42421

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 ) {

Upvotes: 8

Alftheo
Alftheo

Reputation: 888

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

perl faq

Upvotes: 2

Related Questions