Perl Operators   «Prev  Next»
Lesson 7 Boolean and relational operators
ObjectiveWrite 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.

String Relational Operators

OperatorDescription
gt greater than
lt less than
ge greater than or equal to
le less than or equal to

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.
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
}
Operator categoryUsed for
Numeric relational operatorsNumerical comparisons
String relational operators String comparisons
Numerical equality operators Testing numerical equality
String equality operators Testing string equality
Boolean algebraic operators Boolean algebra
Shortcut operators Boolean shortcuts
Ternary operator If/then/else


String Equality Operators

Operator Description
eqequal to
nenot 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

Click the Exercise link below to practice writing conditional code.
Conditional Operators - Exercise

SEMrush Software