AnnaSchumann
AnnaSchumann

Reputation: 1271

IF statement containing OR perl

A very simple question but I can't seem to figure out the problem. Why does this snippet of code successfully print all lines where $F[1] does not equal 83:

    if ($F[1] != 83) {
        print OUT2 "$_\n";
    }

But this snippet (containing an OR statement) simply prints all lines, ignoring both criteria:

    if ($F[1] != 83 || $F[1] != 99) {
        print OUT2 "$_\n";
    }

The desired result was to print all lines where $F[1] contains anything other than 83 or 99.

Upvotes: 0

Views: 298

Answers (2)

Dominique
Dominique

Reputation: 17493

Never forget the following logical rules:

(not (A and B)) == (not(A) or  not(B))

(not (A or B))  == (not(A) and not(B))

Upvotes: 6

ysth
ysth

Reputation: 98398

Since every number is either != 83 or != 99 or both, using || won't work.

Use && instead to get only numbers other than 83 and 99:

if ( $F[1] != 83 && $F[1] != 99 ) {

If you have a longer list to check, you may want to do e.g.:

if ( ! grep $_ == $F[1], 83, 99, 107, 133, 150 ) {

Upvotes: 4

Related Questions