Perl Ternary (Conditional) Operator

ternary operators also conditional operator, that accepts three operands, Conditional expression followed by ?, code statement to execute, if true, followed by a colon :, followed by code statements

Syntax

  condition? if_true_perl_statements_to_execute : if_false_perl_statements_to_execute
  • condition: Valid Perl Conditional expression evaluates to boolean, that returns a boolean value(true or false)
  • if_true_perl_statements_to_execute: Perl statements to execute if condition evaluated to true
  • if_false_perl_statements_to_execute : Perl statements to execute if condition evaluated to false

It is the same as short-hand syntax if else conditional statements.

if (condition) {
    if_true_perl_statements_to_execute;
} else {
    if_false_perl_statements_to_execute;
}

It is useful for developers to reduce code lines and simplify

Perl Ternary Operator Examples

A boolean variable is created initialized and used in the ternary operator.

It prints VALID if it is true(1), else NOT VALID

my $isValid = 1;

$isValid ? print "VALID\n" : print "NOT VALID\n";

Another example to use a comparison operator in a conditional expression. Below, $Agevariable is declared and assigned with a value. These variables are compared with 60 and return the string.

The result is assigned to a variable

Here is an example of a Perl Ternary Operator assignment

my $age = 10;

$result = $age >=60 ? "Senior Citizen" : "Not Senior Citizen";
print "$result\n";

One more example to check in Perl Subroutines

This example contains sub-routines that return the ternary operator result

sub check_age {
    my $age = 50;
    return $age >=60 ? " Senior Citizen" : "Not Senior Citizen";
}

The same can be rewritten using if the else conditional expression

sub check_age {
    my $age = 40;
    my $result;
    if ($age >= 60) {
        $result = "Senior Citizen";
    }
    else {
        $result = "Not Senior Citizen";
    }
    return $result;
}

Another example is, the Perl Conditional operator with multiple conditions

You can use multiple conditions or nested conditions using statements inside ()

my $age=40
print ($age < 10) ? "Child" : ($age < 18) ? "Teenage" : ( $age <60> 18) ? "Man" : "Senior";