Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

question mark in there

by jettero (Monsignor)
on Dec 12, 2000 at 21:16 UTC ( #46275=perlquestion: print w/replies, xml ) Need Help??

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) >= $[

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://46275]
Approved by root
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2022-07-05 09:14 GMT
Find Nodes?
    Voting Booth?

    No recent polls found