If Else in Perl

Branching with if and else in Perl is straightforward.

use strict;
use warnings;

# Here's a basic example.
if (7 % 2 == 0) {
    print "7 is even\n";
} else {
    print "7 is odd\n";
}

# You can have an `if` statement without an else.
if (8 % 4 == 0) {
    print "8 is divisible by 4\n";
}

# Logical operators like '&&' and '||' are often
# useful in conditions.
if (8 % 2 == 0 || 7 % 2 == 0) {
    print "either 8 or 7 are even\n";
}

# A statement can precede conditionals; any variables
# declared in this statement are available in the current
# and all subsequent branches.
my $num = 9;
if ($num < 0) {
    print "$num is negative\n";
} elsif ($num < 10) {
    print "$num has 1 digit\n";
} else {
    print "$num has multiple digits\n";
}

To run the program:

$ perl if-else.pl
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that you don’t need parentheses around conditions in Perl, but they are often used for clarity. Braces are required for multi-line blocks.

In Perl, there is a ternary operator (?:), which can be used for simple conditional expressions:

my $result = (7 % 2 == 0) ? "7 is even" : "7 is odd";
print "$result\n";

This provides a more concise way to write simple if-else statements.