cormanaz has asked for the wisdom of the Perl Monks concerning the following question:

Good day Monks. I am trying to detect duplicate rows in an array by looking at one element, which is a string. The relevant bit of code is:
if ($items[$i][3] =~ /\b$lastitem[3]\b/) { print "DUPLICATE\n"; $dupcount++; }
Problem is, if the match variable contains a regexp special character, like $, it doesn't match. I need to get it to interpret the variable-substituted string literally.

Some kind monks helped me out with a similar problem on the replace side of a substitute statement in this thread, but I can't seem to make the same technique work in the above case. Anyone know how I can solve this problem?

Many thanks

Steve

Replies are listed 'Best First'.
Re: Regexp variable substitution problem in match
by saintmike (Vicar) on Aug 28, 2005 at 01:15 UTC
    To make sure that any regex meta characters in $lastitem[3] are interpreted literally, surround the scalar by \Q...\E:

        /\b\Q$lastitem[3]\E\b/

    will do the trick, just like running quotemeta on the scalar before using it in a regex.

Re: Regexp variable substitution problem in match
by polettix (Vicar) on Aug 28, 2005 at 01:22 UTC
    #!/usr/bin/perl use strict; use warnings; my @against = qw( hi $hi @hi %hi ); foreach my $outer (@against) { foreach (@against) { my $inner = quotemeta; print "[$outer] against [$inner]: "; if ($outer =~ /$inner/) { print "MATCHES\n"; } else { print "NO WAY\n"; } } } __END__ [hi] against [hi]: MATCHES [hi] against [\$hi]: NO WAY [hi] against [\@hi]: NO WAY [hi] against [\%hi]: NO WAY [$hi] against [hi]: MATCHES [$hi] against [\$hi]: MATCHES [$hi] against [\@hi]: NO WAY [$hi] against [\%hi]: NO WAY [@hi] against [hi]: MATCHES [@hi] against [\$hi]: NO WAY [@hi] against [\@hi]: MATCHES [@hi] against [\%hi]: NO WAY [%hi] against [hi]: MATCHES [%hi] against [\$hi]: NO WAY [%hi] against [\@hi]: NO WAY [%hi] against [\%hi]: MATCHES

    Flavio
    perl -ple'$_=reverse' <<<ti.xittelop@oivalf

    Don't fool yourself.