control-flow intermediate

How to use the ternary operator ?: in Perl?

Question

How to use the ternary operator ?: in Perl?

The ternary operator ?: in Perl is a concise conditional operator that acts as a shorthand for an if-else statement. It evaluates a condition and returns one of two expressions depending on whether the condition is true or false. This operator is very handy for simple conditional assignments or inline decisions within expressions.

Syntax

The basic syntax of the ternary operator is:


condition ? expression_if_true : expression_if_false

Here, the condition is evaluated in scalar context. If it is true (Perl's definition of truth), the result of the whole expression is the value of expression_if_true. Otherwise, it returns the value of expression_if_false.

Differences from if-else

  • Expression context: The ternary operator returns a value and can be used inside other expressions, e.g., assignments or interpolations.
  • Conciseness: It reduces multiple lines of an if-else block to one line.
  • Precedence: Be mindful of operator precedence; using parentheses can eliminate ambiguity.

Key Perl Concepts Illustrated

  • condition: Tested in scalar context.
  • ?: operator returns a scalar (or list in list context) depending on branches.
  • Because Perl embraces TMTOWTDI ("There's more than one way to do it"), you can often replace ternary operators with if-else or logical operators, but the ternary is best for clear, concise conditional expressions.

Example: Using the Ternary Operator in Perl

The example below reads a number, checks whether it is even or odd, and prints the result using the ternary operator:


#!/usr/bin/perl
use strict;
use warnings;

print "Enter a number: ";
chomp(my $num = <STDIN>);

# Use ternary operator to decide even/odd label
my $result = ($num % 2 == 0) ? "even" : "odd";

print "The number $num is $result.\n";

Running this script:


Enter a number: 7
The number 7 is odd.

Common Pitfalls and Gotchas

  • Precedence issues: The ternary operator has low precedence, so it is good practice to use parentheses around the condition and the expressions to avoid ambiguity.
  • Chaining ternary operators: You can nest ternaries but it often hurts readability:

my $grade = ($score >= 90) ? "A"
          : ($score >= 80) ? "B" 
          : "C";

Use nesting sparingly and with proper indentation.

  • Context awareness: In list context, ternary can return lists; in scalar context, it returns scalar values.
  • Readability: For complex conditions, traditional if-else blocks are often clearer.

Summary

The ternary operator ?: in Perl is a succinct way to write simple conditional expressions. It improves code brevity and is ideal for inline decisions but should be used judiciously for readability. Always consider precedence and context when using it.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 5ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)
STDERR
(empty)

Was this helpful?

Related Questions