Lesson 7 | Boolean and relational operators |
Objective | Write a program that uses conditional operators to process a yes/no question. |
Boolean and Relational Operators
Click on each of the links below to read more about the boolean and relational operators used in Perl.
Note: In order to complete this lesson's exercise, you must be familiar with these operators.
Perl String Relational Operators
Operator | Description |
gt | greater than |
lt | less than |
ge | greater than or equal to |
le | less than or equal to |
The string relational operators are used to test relationships between strings. For example,
if($s1 gt $s2) {
some code here
}
else {
some other code here
}
Strings are evaluated based on their ASCII value (so a
is greater than A
) and spaces are significant. These operators test the relative value of string data.
It is an error to use these operators with numbers.
Perl 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.
Conditional Operators - Exercise