Easy Tutorial
❮ Perl Goto Statement Perl Next Statement ❯

Perl IF...ELSIF Statement

Perl Conditional Statements

An if statement can be followed by an optional elsif statement, and then another else statement.

This conditional structure is very useful in cases with multiple conditions.

When using if, elsif, and else statements, you need to keep the following points in mind:

Syntax

The syntax is as follows:

if(boolean_expression 1){
   # Executed when boolean_expression 1 is true
}
elsif(boolean_expression 2){
   # Executed when boolean_expression 2 is true
}
elsif(boolean_expression 3){
   # Executed when boolean_expression 3 is true
}
else{
   # Executed when all the above conditions are false
}

Example

#!/usr/bin/perl

$a = 100;
# Using == to check if two values are equal
if( $a == 20 ){
    # Executed when the condition is true
    printf "The value of a is 20\n";
}elsif( $a == 30 ){
    # Executed when the condition is true
    printf "The value of a is 30\n";
}else{
    # Executed when all the above conditions are false
    printf "The value of a is $a\n";
}

Executing the above program will output:

The value of a is 100

Perl Conditional Statements

❮ Perl Goto Statement Perl Next Statement ❯