Perl - Boolean Expressions
In a Nutshell - CIW Course Section 2, Part B1, Chapter 3
Boolean Expressions
A Boolean expression is an expression that evaluates to a true or false value. However, in Perl, if an expression evaluates to false nothing is returned. So, in Perl a Boolean Expression will evaluate to true (1) or nothing.
Numeric Boolean Expressions
When comparing two numeric values, Perl has a number of numeric Boolean operators to make the comparison.
| Numeric Boolean Operators | |
|---|---|
| Operator | Description |
| = = | Equal to |
| != | Not equal to |
| > | Greater than |
| >= | Greater than or equal to |
| < | Less than |
| <= | Less than or equal to |
When making a Boolean comparison, the left operand is compared to the right operand and true will be returned if the comparison condition is met.
String Boolean Expressions
String comparisons are done in the same way as numeric comparisons, but use a different set of operators.
| String Boolean Operators | |
|---|---|
| Operator | Description |
| eq | Equal to |
| ne | Not equal to |
| gt | Greater than |
| ge | Greater than or equal to |
| lt | Less than |
| le | Less than or equal to |
I did a little experimenting to see how these comparisons are reached, and discovered that it only seems to compare the first character of the string, unless the initial characters are the same.
"sam" is less than "tom", "sww" is less than "tom" and "tom" is less than "tommy".
Logical Operators
Logical operators allow the combining of Boolean expressions to provide greater flexibility and more advanced decision making.
| Logical Operators | ||
|---|---|---|
| Operator | Logical | Description |
| && | AND | Both expression1 and expression2 must be true |
| xor | XOR | Only expression1 or expression2 must be true |
| | | | OR | If both expression1 and expression2 are false the logical will return false |
| ! (exclamation) | NOT | Inverts the logical value of the operand to it's right |
Syntax is: expression1 <logical> expression2
Example: If ($a = 10 && $b = 5) {
The above expression requires that both A equals 10 AND B equals 5 to evaluate to true.

