Ternary operator A ? B : C
Perl has a ternary operator that return the value depending on the condition.
Condition ? ValueIfTrue : ValueIfFalse
Ternary operator example:
If $flag is 1 which is a true value, the ternary operator returns 3.
my $flag = 1; my $num = $flag ? 3 : 5;
my $flag = 0; my $num = $flag ? 3 : 5;
If $flag is 0 which is a false value, the ternary operator returns 5.
I think the ternary operator is a little difficut to read until you are familiar with it. Looking only at the first half, it may seem that $flag is assigned to $num.
If you want to know more about the Perl boolean, see the following article.
What is the difference from if statment?
What can be written with the ternary operator can be written with if statement.
my $flag = 1; my $num; if ($flag) { $num = 3; } else { $num = 5; }
The differences are that the ternary operator is one line and returns a value.
Taking advantage of this, for example, you can write it like this in the template of Mojolicious
<%= $flag ? 3 : 5 %>
Ternary operator with multiple conditions
The ternary operator supports multiple conditions.
my $flag = 1; my $num = $flag == 1 ? 3 : $flag == 2 ? 5 : 7;
It's a little difficult to read.
- If $flag is 1, 3 will be returned.
- If not, the value after ":" will be returned
- If $flag is 2, 5 will be returned.
- If not, the value after ":" will be returned. In other words, 7 will be returned.
Example program
This is an example program of the ternary operator.
use strict; use warnings; # Ternary operator my $num1 = 1; my $num2 = 2; print "1. Example of ternary operator (replace if ~ else)\n"; my $max_num = $num1 > $num2 ? $num1: $num2; print "\$max_num = $max_num\n\n"; # Same as the following if ~ else statement if ($num1 > $num2) {$max_num = $num1} else {$max_num = $num2} my $age = 23; print "2. Example of ternary operator (replace if ~ elsif ~)\n"; my $generation = $age < 20?'Child': $age < 60?'middle': $age < 80?'old': 'very old'; print "\$generation = $generation\n"; # Same as the following if ~ elsif statement if ($age < 20) {$generation = 'child'} elsif ($age < 60) {$generation = 'middle'} elsif ($age < 80) {$generation = 'old'} else {$generation = 'very old'}
Output:
1. Example of ternary operator (replace if ~ else) $max_num = 2 2. Example of ternary operator (replace if ~ elsif ~) $generation = middle