In the Perl programming language, there is one operator that works with three operands.
The ternary operator is 2 characters ?:
, and these symbols are recorded are not near, and between
operands.
The ternary operator returns either the second or the third operand depending on the value
of the first operand. If the first operand is true, then returns the second operand
if the first operand is false, then it returns the third operand
(read more about the true and false in Perl).
▶ Run
my $var = 1 ? 100 : 200;
print $var;
The program will display the number 100
.
The first operand 1
is true so the result of the operator is the second operand, i.e.
the number 100
. This value is assigned to a variable and displayed on the screen.
Instead of the ternary operator can be used if-else
. Here is a program that works well
same as the previous:
▶ Run
my $var;
if (1) {
$var = 100;
} else {
$var = 200;
}
print $var;
Sometimes it is more convenient to use a ternary operator, and sometimes the design if-else
.