0

I have the below if statement, the '!=' isn't working. The second if statement in this line of code will not work, can someone tell me why?

    if ($line =~ $search) {
        print "$line <br> <br>";     
    }
}
if ($line != $search) { #This if statement will not work
    print "word is not in file";
}
TLP
  • 66,756
  • 10
  • 92
  • 149
TheHadimo
  • 147
  • 1
  • 1
  • 8
  • What does "not work" mean? Have you used Data::Dumper or similar module to dump both vars to see what they contain? – Ron Bergin Nov 14 '14 at 22:25
  • possible duplicate of [How do I compare two strings in Perl?](http://stackoverflow.com/questions/1175390/how-do-i-compare-two-strings-in-perl) – John Kugelman Nov 14 '14 at 22:25
  • 2
    The opposite of `if ($line =~ $search)` is `else ...`. – TLP Nov 15 '14 at 00:39

2 Answers2

3

The == and != operators compare the operands as numbers. The operators for string comparisons are eq and ne.

Reference: http://perldoc.perl.org/perlop.html#Equality-Operators

Joni
  • 108,737
  • 14
  • 143
  • 193
2

Actually, if you are looking for the opposite of =~,

you do not want ne or eq, but !~ as in

if ( $line !~ $search )

Also, beware of special ( for regex ) characters in $search.

perl regex doc

bytepusher
  • 1,568
  • 10
  • 19