- 论坛徽章:
- 0
|
2.6.1. Boolean Values
You may use any scalar value as the conditional of the if control structure. That's handy if you want to store a true or false value into a variable, like this:
$is_bigger = $name gt 'fred';
if ($is_bigger) { ... }
But how does Perl decide whether a given value is true or false? Perl doesn't have a separate Boolean data type as some languages have. Instead, it uses a few simple rules:[*]
[*] These aren't the rules Perl uses but are rules you can use to get the same result.
If the value is a number, 0 means false; all other numbers mean true.
If the value is a string, the empty string ('') means false; all other strings mean true.
If the value is another kind of scalar than a number or a string, convert it to a number or a string and try again.[]
[] This means that undef (which we'll see soon) means false, and all references (which are covered in the Alpaca book) are true.
There's one trick hidden in those rules. Because the string '0' is the same scalar value as the number 0, Perl has to treat them the same. That means that the string '0' is the only nonempty string that is false.
If you need to get the opposite of any Boolean value, use the unary not operator, !. If what follows it is a true value, it returns false; if what follows is false, it returns true:
if (! $is_bigger) {
# Do something when $is_bigger is not true
} |
|