Perl does not have a special "Boolean" type. But Perl often returns true or false.
In Perl, every expression is considered true except for the following cases:
- Number 0.
- Empty string ("")
- undef - undefined (The value of a variable is undef if it is not initialized.)
- '0' - String containing a single 0 digit
Now, see this chart for general Boolean operations:
Exp1 | Operator | Exp2 | Boolean |
---|---|---|---|
True | AND | True | True |
True | AND | False | False |
False | AND | False | False |
True | OR | True | True |
True | OR | False | True |
False | OR | False | False |
So, if we use AND with any two operands and if both of them are True, then the result is True. Otherwise, it is False
And if we use OR and if any of the two operands is True, then the result is True and it is False if both the operands are False.
'AND' can be understood as both ( first and second both )
'OR' can be understood as either ( any of the first or second ). See the next line to understand it more clearly.
True OR False -> As 'OR' is used, either of the two is true -> True
True AND False -> As 'AND' is used, both are not true -> False
Try to understand this or just remember the chart.
Now, let's use these in a mathematical operation to understand their use.
So, 2>5 AND 10>7 is False. (2>5 is False, 10>7 is True)
2>5 OR 10>7 is True.
NOT
NOT reverses the value of a Boolean. It means that NOT(True) is False and NOT(False) is True.
I hope that now you know about Booleans and their uses. So, let's use these in Perl.
Operators used in Perl for this purpose are:
Assume that 'a' is true and 'b' is false.
Operator | Description | Example |
---|---|---|
&& | C-style Logical AND operator | ($a && $b) is false |
|| | C-style Logical OR operator | ($a || $b) is true |
and | Logical AND operator | ($a and $b) is false |
or | Logical OR operator | ($a or $b) is true |
! | C-style Logical NOT operator | !($a) is false |
not | Logical NOT operator | not($a) is false |
Let's see an example of these operators:
$a = true;
$b = false;
$c = ($a and $b);
print $c,"\n";
$c = ($a && $b);
print $c,"\n";
$c = ($a or $b);
print $c,"\n";
$c = ($a || $b);
print $c,"\n";
$a = 0;
print !($a),"\n";
$c = not($a);
print $c,"\n";
false
true
true
1
1
You will learn about different operators in the next chapter.