How to use postfix if in Perl?

Question

How to use postfix if in Perl?

In Perl, the postfix if is a concise and idiomatic way to write conditional code. Instead of writing a traditional if statement with a block, you can append the condition after the statement using the if modifier. This makes the code shorter and often easier to read, especially when executing simple actions conditionally.

What is postfix if?

Normally, an if statement in Perl uses this syntax:


if (condition) {
    statement;
}

The equivalent using a postfix if looks like this:


statement if condition;

This executes statement only if condition evaluates to true (Perl's concept of truth includes defined/non-zero values). It is especially useful for short, simple conditions.

Example of postfix if in Perl


use strict;
use warnings;

my $number = 10;

print "Number is greater than 5\n" if $number > 5;

# This line will only print if $number <= 5
print "Number is 5 or less\n" if $number <= 5;

Running this script will output:

Number is greater than 5

This demonstrates how Perl executes the print statement only when the condition after if is true.

Key Points About Postfix if

  • It works on any statement or expression that returns a value.
  • It is good for short, simple conditional statements.
    For complex conditionals or multiple statements, the standard block if is usually clearer.
  • Context matters: In scalar context, the expression returns the value of the statement if the condition is true, else undef.
  • Readability: Overusing postfix ifs in complicated code may reduce readability, so use them judiciously.
  • Chained postfix ifs: You cannot chain multiple postfix if modifiers directly on the same statement; use regular if/elsif/else instead.

Common Pitfalls

  • Don't try to use postfix if with multiple statements; it only applies to a single statement.
    For example, print "A"; print "B" if $cond; only applies the condition to the second print.
  • Using postfix modifiers with else is not possible; you must use the full if/else block.
  • Writing very long or nested postfix ifs can make code harder to read.

Summary

Perl's postfix if is a neat shortcut for writing if conditions inline after a statement, ideal for simple, single-line conditions. It leverages Perl's motto of "There's more than one way to do it" (TMTOWTDI) by providing a more compressed and idiomatic control flow.

Verified Code

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

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

Was this helpful?

Related Questions