1. Perl
  2. Syntax
  3. here

if ~ elsif ~ else - Multiple conditional branch

You can use a if statement for a conditional branch. If the condition is true, the inside of the block is executed.

if (condition) {
  ...
}

elsif

You can also use elsif to make multiple conditional branches.

if (condition1) {
  ...
}
elsif (condition2) {
  ...
}

More conditinal branches.

if (condition1) {
  ...
}
elsif (condition2) {
  ...
}
elsif (condition3) {
  ...
}

else

If you use else, you can create the branch executed if the condition is not met.

if (condition) {
  ...
}
else {
  # Do the things if the condition is not met
}

A combination with elsif statements:

if (condition1) {
  ...
}
elsif (condition2) {
  ...
}
elsif (condition3) {
  ...
}
else {

}

Please see below for details on how to use conditional branch using if statement.

If statement example

It is an example of if ~ else and if ~ elsif.

use strict;
use warnings;

# Conditional branch if ~ else

print "1: if ~ else statement\n";
my $num = 2;
if ($num == 1) {
  # Not effective
}
else {
  print "\$num is not 1.\n\n";
}

# Conditional branch if ~ elsif ~ elsif ~
print "2: if ~ elsif ~ elsif ~ else\n";
if ($num == 1) {
  # Not effective
}
elsif ($num == 2) {
  print "\$num is 2\n\n";
}
elsif ($num == 3) {
  # Not effective
}
else {
  # Not effective
}

Output:

1: if ~ else statement
$num is not 1.

2: if ~ elsif ~ elsif ~ else
$num is 2

Related Informatrion