-1

I am trying to match two things which both are full of metacharacters that needs to be used as 'Literal' in my match pattern. \Q is suppose to quote all metacharacter in a string until \E...but it doesn't work.

Whats up with that?

this is the line that gives me trouble : if (/\Q$prev\E/ !~ /\Q$ww[0]\E/) {

Toto
  • 83,193
  • 59
  • 77
  • 109
  • 4
    You can't compare two regular expressions like that. Could you post more of your code and clarify what you are trying to do? – MattLBeck Feb 28 '12 at 16:39
  • 3
    What do you mean by "it doesn't work"? Do you want `$prev` and `$ww[0]` to be interpolated or don't you? – reinierpost Feb 28 '12 at 16:40
  • What makes you think that the metaquoting isn't happening? You might want to see [Understand the order of operations in double quoted contexts](http://www.effectiveperlprogramming.com/blog/1496) for some ways you can explore that. – brian d foy Feb 29 '12 at 02:04

2 Answers2

11

Absent the use of =~ or !~,

/.../

is short for

$_ =~ m/.../

so

/\Q$prev\E/ !~ /\Q$ww[0]\E/

is short for

($_ =~ /\Q$prev\E/) !~ /\Q$ww[0]\E/

which is equivalent to one of the following depending on whether the left regex match succeeds or not:

"" !~ /\Q$ww[0]\E/
"1" !~ /\Q$ww[0]\E/

You simply want:

$prev !~ /\Q$ww[0]\E/   # $ww[0] doesn't contains $prev

If you actually want

$prev !~ /^\Q$ww[0]\E\z/   # $ww[0] isn't equal to $prev

then you can simplify that to

$prev ne $ww[0]   # $ww[0] isn't equal to $prev

By the way, always use use strict; use warnings;. It may have identified a problem here (but not necessarily, depending on the value of $_).

ikegami
  • 322,729
  • 15
  • 228
  • 466
2

It looks like you want to compare a string in $prev to one in $ww[0]. If this is the case, a regex match should look like this:

$result = $prev !~ /\Q$ww[0]\E/

$result will return 1 if $prev is not the same as whatever is in www[0], ignoring metacharacters.

However if that is all you wanted to do, you might as well use ne:

if ($prev ne $ww[0]){ 
   #do this if $prev and $ww[0] are not the same
} 

Also, as @toolic has mentioned, add the following line to the top of your script:

use warnings;

This will give you some feedback on possible problems in your scripts.

MattLBeck
  • 5,301
  • 4
  • 36
  • 55
  • Thanks a lot guys for your help!! I was over complicating things as usual :). ($prev ne $ww[0]) worked just fine. – user1238319 Feb 28 '12 at 17:33