Logical and comparison operators
Before we introduce the corresponding Perl operators here are the basics of Boolean algebra.
Boolean algebra is a variant of algebra where instead of numbers are truth values 0
and 1
,
where 1
is called truth
,
and 0
is called false
.
Like in a normal algebra there are operations like +
,
*
etc,
the basic ones are called NOT
,
AND
and OR
.
As you already know in Boolean algebra we have only Truth
and False
values.
That means that not only they can be used in different operations,
but also the result of those operations is either Truth
or False
.
Let's look at them one by one.
Truth and False
There are no Truth
and False
values in Perl.
In Perl Truth
is everything that is not False
where False
is everything that converts to 0
: 0
itself,
''
(empty string),
undef
for example.
NOT
NOT
operator is a unary operator,
which means it operates on one value.
In Perl NOT
operator is !
.
NOT
truth table:
x | !x |
0 | 1 |
1 | 0 |
Let's see what are the results of using this operator on various values.
In the following example we add 0
to False
values so they are not converted to empty strings by say
function.
say !0; say !1 + 0; say !'string that converts to 1' + 0; say !'';
AND
AND
operator is a binary operator, which means it operates on two values. In Perl AND
operator is &&
. AND
truth table:
x | y | && |
0 | 0 | 0 |
1 | 0 | 0 |
0 | 1 | 0 |
1 | 1 | 1 |
Let's see what are the results of using this operator on various values. In the following example we add 0
to False
values so they are not converted to empty strings by say
function.
say 1 && 1; say 0 && 1; say 0 && 0; say 'string' && 1;
OR
OR
operator is also a binary operator, which means it operates on two values. In Perl OR
operator is ||
. OR
truth table:
x | y | || |
0 | 0 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
1 | 1 | 1 |
Let's see what are the results of using this operator on various values. In the following example we add 0
to False
values so they are not converted to empty strings by say
function.
say 1 || 1; say 0 || 1; say 0 || 0; say 'string' || 0;
Priority
As in a normal algebra the operators in Boolean algebra have their priority, where different operators are evaluated earlier than others. Order of Boolean operators:
! && ||
Combinations
NOT
, AND
and OR
can be combined altogether. You can use also brackets to change the order of logical flow:
say (1 || 0) && 1
Exercise
Fix the following statement by introducing brackets so it prints empty string instead of 1
.
say !1 || 1 && 1
Comparison operators
Comparison operators also return True
and False
but are used with numbers and strings. Because Perl does not distinguish between numbers and strings there are two separate groups of comparison for numbers and strings.
== | != | < | <= | > | >= |
eq | ne | lt | le | gt | ge |
Let's try this example:
say 1 == 1; say 10 > 2; say 3 <= 3; say 'foo' ne 'bar';