http://qs1969.pair.com?node_id=46275

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

my first question today worked out so well already... Here's another. :)

I don't want the '?' to get used as an optional marker thingy in the regexp... I instead want to see if $b is in $a... Help me make this work?

sh$ perl -e '$a = $b = "word?dude"; print "$a $b\n" if $a =~ m/$b/'

Replies are listed 'Best First'.
Re: question mark in there
by runrig (Abbot) on Dec 12, 2000 at 21:19 UTC
    If you just want to see if a string is in another string, then use index. If you still feel a burning need to use a regex, then use quotemeta on b.
Re: question mark in there
by kilinrax (Deacon) on Dec 12, 2000 at 21:19 UTC
    Just use \Q to quote out the '?' character:
    abowley@lave:~$ perl -e '$a = $b = "word?dude"; print "$a $b\n" if $a +=~ m/\Q$b/' word?dude word?dude
      That's not necessarily a bad way to do it, but everyone should be aware that if there are any metacharacters in $b and \E precedes them, the metacharacters will be parsed as metacharcters.
      IOW, if $b == "???\E?", the fourth '?' will be not be matched literally.

      The only real advantage to punk music is that nobody can whistle it.
        I was skeptical about this warning, and a simple experiment shows that it is not accurate:
        DB<1> $x = '???\E???' DB<2> p "\Q$x" \?\?\?\\E\?\?\? DB<3>
        A \Q cannot be ended by a \E in an interpolated string. And, using B::Deparse's -q option in 5.6, we can see why:
        ~> perl -MO=Deparse,-q -e '$x = q{?\E?}; $y = "a\Q$x\Eb"; print "$y\n" +' $x = '?\\E?'; $y = quotemeta $x; print $y . "\n"; -e syntax OK
        This shows that \Q\E inside a double-quoted string is actually compiled as concatenation and quotemeta. The value of $x at runtime won't change the scope of the quotemeta().
Re: question mark in there
by I0 (Priest) on Dec 12, 2000 at 21:57 UTC
    $a =~ m/\Q$b\E/ or index($a,$b) >= $[