What is the ternary operator in Pearl?

Overview

In Pearl, we use ternary operators so we don't have to use the if-else statement. The operator makes the codes look nice and clean, which makes them easy to understand.

One of the most apparent important use of a ternary operator is that it replaces the use of the if-else state in a more clean, readable, and short form.

Syntax

cond ? val if true : val if false
Syntax

Parameters

  • cond: This is the code/expression whose output defines the value that is used.
  • The value after the ? is returned if the condition returns true.
  • The value after the : is returned if the condition returns false.

Example

print(1==0 ? 'right' : 'wrong',"\n");

Explanation

  • Line 1: We use the ternary operator to check if 1 is equal to 0. This is definitely false, and that's why the wrong message displays.

Free Resources