The ? : Operator in Perl

PERLServer Side ProgrammingProgramming Scripts

Let's check the conditional operator? : in Perl which can be used to replace if...else statements. It has the following general form −


Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

The value of a? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. Below is a simple example making use of this operator −


 Live Demo

$name = "Ali";
$age = 10;
$status = ($age > 60 )? "A senior citizen" : "Not a senior citizen";
print "$name is - $status\n";


This will produce the following result −

Ali is - Not a senior citizen
Updated on 29-Nov-2019 06:01:59