How to use if-else conditional in Perl?

Question

How to use if-else conditional in Perl?

In Perl, the if-else conditional statement is a fundamental control structure that allows you to execute different blocks of code based on whether a condition is true or false. Perl, being a flexible and expressive language, provides several ways to write conditionals, but the basic if-else syntax is straightforward.

Basic if-else Syntax

  • if (condition) { ... } runs the block only if the condition evaluates to true.
  • else { ... } runs the block if the if condition was false.
  • You can also chain multiple conditions with elsif for multiple branches.

Perl conditions are usually expressions that return true or false in boolean context. In Perl, the following are false in boolean context: undef, 0, the empty string (""), and the string "0". Everything else is true.

Perl-Specific Notes

  • Sigils: Variables have sigils like $ for scalars ($x), @ for arrays, and % for hashes, but conditions themselves evaluate scalars.
  • Context: Conditions are evaluated in scalar (boolean) context.
  • TMTOWTDI: Perl offers many ways to write conditionals, including postfix if and ternary operators, but the classic block form is often clearest for beginners.

Example: Using if-elsif-else

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

# Define a variable with a numeric value
my $num = 42;

if ($num > 50) {
    print "The number $num is greater than 50.\n";
}
elsif ($num == 42) {
    print "The number is exactly 42.\n";
}
else {
    print "The number $num is 50 or less, and not 42.\n";
}

When you run this script, it will print:

The number is exactly 42.

Common Pitfalls

  • For equality, use == for numeric comparison, not = (assignment), and not eq which is for string comparison.
  • Remember to use parentheses () around the condition.
  • Use curly braces {} to delimit the blocks, even if optional in some cases, to improve readability and avoid bugs.
  • Don't confuse elsif with else if. elsif is the Perl keyword to extend if.

Summary

Perl's if-else statements let you control your program's flow based on conditions. Use if to check a condition and run code, elsif for additional conditions, and else for the fallback case. Combine this with Perl's scalar context and careful use of comparison operators to write effective conditionals.

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
The number is exactly 42.
STDERR
(empty)

Was this helpful?

Related Questions