The ternary operator ?: in Perl

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).

Here's an example:

▶ Run
#!/usr/bin/perl

my $var = 1 ? 100 : 200;

print $var;

The program will display the number 100.

  • Is first written to the first operand, in this example, the number 1
  • Then there is a symbol ?
  • Then recorded the second operand 100
  • Then there is a symbol :
  • Then is recorded the third operand 200

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
#!/usr/bin/perl

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.

Other articles

Comments