Search⌘ K

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.

Perl
$a=5; #Change values of $a and $b to change output of the code.
$b=2;
($a > $b) ? print "$a is greater than $b" : print "$a is NOT greater than $b";

Explanation

In the code above:

  • The variables $a and $b are 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 $a will not be greater than $b

  • At the end, the output displayed will be: 2 is NOT greater than 5