Quick summary of conditions and comparisons in Perl
Recall, a condition can be thought of as something that is true or false. It is useful as part of control flow constructs such is if, if-else or while.
A condition can be as simple as a scalar value -- a number or a string.
- For numbers,
- Zero (0) is false
- All other numbers are true
- For strings,
- An empty string (e.g., "" or '') and the string "0" are false
- All other strings are true
Comparison operators for numbers and strings are also useful.
For numbers | For strings | Meaning |
== | 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 |
<=> | cmp | Less than, equal to, or greater than (-1,0,+1) |
Logical operators can be used to negate or combine conditions.
- (![cond]) is true if condition [cond] is false, and vice-versa.
(More specifically, ! of something true produces the empty string
- ([cond1] && [cond2]) is true if condition [cond1] is true and condition [cond2] is true, and false otherwise.
- ([cond1] || [cond2]) is true if condition [cond1] is true or if condition [cond2] is true, and false otherwise.
- ! takes precedence over && and ||, so for example (![cond1] && [cond2]) is true if [cond1] is false and [cond2] is true.
Full rules on operator and comparison precedence can be found here. When in doubt, the simple approach is to use parentheses ().
The ASCII character table: