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!";
} |
$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; |
&& 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.
|
| Contents |
Next |