Logical Operators

To combine comparisons, use the and, or and not logical operators. In some scripts, you might see their cryptic cousins, &&, || and !:

Lower precedence Higher precedence Description
$a and $b $a && $b TRUE if $a AND $b are TRUE
$a or $b $a || $b TRUE if either $a OR $b are TRUE
not $a !$b TRUE if $a is FALSE


if ($a < 100 and $a > 0) {
  print "a is the right size\n";
} else {
  die "out of bounds error, operation aborted!";
}

if ($a < 100 && $a > 0) {
  print "a is the right size\n";
} else {
  die "out of bounds error, operation aborted!";
}

if ($a >= 100 or $a <= 0) {
  die "out of bounds error, operation aborted!";
}

if ($a >= 100 || $a <= 0) {
  die "out of bounds error, operation aborted!";
}

To Reverse Truth, use not or !


  $ok = ($a < 100 and $a > 0);
  print "a is too small\n" if not $ok;

  # same as this:
  print "a is too small\n" unless $ok;

  # and this:
  print "a is too small\n" if !$ok;

and vs &&, or vs ||

&& has higher precedence than and. || has higher precedence than or. This is an issue in assignments:

Low precedence operation:


  $ok = $a < 100 and $a > 0;

  # This doesn't mean:
  $ok = ($a < 100 and $a > 0);

  # but:
  ($ok = $a < 100) and $a > 0;

High precedence operation:

  $ok = $a < 100 && $a > 0;

  # This does mean
  $ok = ($a < 100 && $a > 0);

When in doubt, use parentheses.


<< Previous
Contents >> Next >>

Lincoln D. Stein, lstein@cshl.org
Cold Spring Harbor Laboratory
Last modified: Wed Oct 11 20:52:17 EDT 2000