In this third part of a five-part series on scalars in Perl, we continue our study of operators, moving on to Boolean and string operators. This article is excerpted from chapter two of the book Beginning Perl, written by James Lee (Apress; ISBN: 159059391X).
As well as being able to evaluate the truth and falsehood of some statements, we can also combine such statements. For example, we may want to do something if one number is bigger than another and another two numbers are the same. The combining is done in a very similar manner to the bitwise operators we saw earlier. We can ask if one value and another value are both true, or if one value or another value are true, and so on.
The operators even resemble the bitwise operators. To ask if both truth values are true, we would use&&instead of&.
So, to test whether 6 is more than 3 and 12 is more than 4, we can write
6 > 3 && 12 > 4
To test if 9 is more than 7 or 8 is less than 6, we use the doubled form of the|operator,||:
9 > 7 || 6 > 8
To negate the sense of a test, however, use the slightly different operator!; this has a higher precedence than the comparison operators, so use parentheses. For example, this tests whether 2 is not more than 3:
while this one tests whether!2is more than 3:
2is a true value.!2is therefore a false value, which gets converted to 0 when we do a numeric comparison. We’re actually testing if 0 is more than 3, which has the opposite effect to what we wanted.
Instead of those forms,&&,||, and!, we can also use the slightly easier-to-read versions,and,or, andnot. There’s alsoxor, for exclusive or (one or the other but not both are true), which doesn’t have a symbolic form. However, you need to be careful about precedence again:
This prints, somewhat surprisingly, the following:
$ perl bool6.pl Useless use of a constant in void context at bool6.pl line 5. Test one: Test two: 1$
We can tell from the presence of the warning about line 5 and from the position of the prompt that something is amiss (or least Unix users can—Windows users need to be a bit more alert since Windows automatically adds a newline character at the end of the program so the system prompt will be on the next line, but the blank line that is expected will not be there). Notice the second newline did not get printed. The trouble is,andhas a lower precedence than&&. What has actually happened is this:
print("Test two: ", 6 > 3) and (3 > 4, "\n");
Now, 6 is more than 3, so that returned 1,print()then returned 1, and the rest was irrelevant.