Lesson 7 | Boolean and relational operators |
Objective | Write a program that uses conditional operators to process a yes/no question. |
Perl Boolean and Relational Operators
The following section discusses more about the boolean and relational operators used in Perl.
Perl Ternary Operators
In computer programming, the following notation
?: is a
ternary operator that is part of the syntax for basic conditional expressions. It is commonly referred to as the conditional operator or ternary if.
Operator |
Description |
? : |
if then else |
The ternary operator uses three expressions to do its work:
$x = $a ? $b : $c
This operator evaluates from left to right:
$a
is evaluated.
- If
$a
is nonzero, $b
is evaluated and returned.
- Otherwise,
$c
is evaluated and returned.
So, given this:
$a = 1; $b = 2; $c = 3;
$x = $a ? $b : $c;
The value of
$b
(2) is assigned to
$x
. If
$a
were zero or undefined, the value of
$c
would be assigned to
$x
.
Note that if
$a
evaluates to true (non-zero), then
$b
will be evaluated, but
$c
will not.
If
$a
evaluates to false (zero), then
$c
will be evaluated but
$b
will not.
Thus you should not write code using the ternary operator that depends on both
$b
and
$c
being evaluated.
String Equality Operators
Operator |
Description |
eq | equal to |
ne | not equal to |
The string equality operators are used to test equality between strings. For example,
while($s ne 'error')
{ some code here }
These operators work with string data.
It is an error to use these operators with numbers.
Understanding Boolean Operators
You use Boolean operators to determine if a value or expression is true or false. Because Perl lets you assign strings and numbers to variables, the Boolean operators are separated into string and numeric versions. You learn the string versions first. you see the if/else statement now just so you can understand how they work.
The if statement takes an expression in parentheses and, if it evaluates as true, executes the code in the block following it.
If an else block follows the if block, the else block executes only if the if expression evaluates as false. For example:
my ( $num1, $num2 ) = ( 7, 5 );
if ( $num1 < $num2 ) {
print "$num1 is less than $num2\n";
}
else {
print "$num1 is not less than $num2\n";
}
That code prints 7 is not less than 5. The < Boolean operator is the Boolean
less than operator and returns true if the left operand is less than the right operand. Now that you have this small example out of the way, the following sections discuss the boolean operators.
Note: In order to complete this lesson's exercise, you must be familiar with these operators.
Conditional Operators - Exercise