home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam

## 10.9. Logical Operators

```if (\$dessert{'cake'} && \$dessert{'ice cream'}) {
# Both are true
print "Hooray! Cake and ice cream!\n";
} elsif (\$dessert{'cake'} || \$dessert{'ice cream'}) {
# At least one is true
print "That's still good...\n";
} else {
# Neither is true - do nothing (we're sad)
}```

There may be a shortcut. If the left side of a logical AND operation is false, the whole thing is false, since logical AND needs both sides to be true in order to return true. In that case, there's no reason to check the right side, so it will not even be evaluated. Consider what happens in this example if \$hour is 3:

```if ( (9 <= \$hour) && (\$hour < 17) ) {
print "Aren't you supposed to be at work...?\n";
}```

Similarly, if the left side of a logical OR operation is true, the right side will not be evaluated. Consider what happens here if \$name is fred:

```if ( (\$name eq 'fred') || (\$name eq 'barney') ) {
print "You're my kind of guy!\n";
}```
```if ( (\$n != 0) && (\$total/\$n < 5) ) {
print "The average is below five.\n";
}```

In that example, the right side will be evaluated only if the left side is true, so we can't accidentally divide by zero and crash the program.