Ternary Operator
Explore how to use the Perl ternary operator to write concise conditional statements. This lesson helps you understand how to perform quick evaluations and execute different code based on true or false conditions, simplifying your Perl code.
We'll cover the following...
The ternary operator is a comparison operator and it executes different statements based on a condition being true or false.
The ternary operator is shorthand syntax for
if-else.
It allows to quickly test a condition and often
replaces a multi-line if statement, making your code more compact.
Syntax
Here’s the syntax:
Example
Let’s take a look at an example which uses ternary operators.
Explanation
In the code above:
-
The variables
$aand$bare set to 5 and 2 -
In line 4, condition
($a > $b)evaluates to true -
Hence, expression 1 executes and the output dispayed is: 5 is greater than 2
You can try changing the values of $a and $b to 2 and 5.
-
Now expression 2 will execute since the condition will evaluate to false this time as
$awill not be greater than$b -
At the end, the output displayed will be: 2 is NOT greater than 5