Perl Else If Statement


Perl Else If Statement

In this tutorial, we will learn about else-if statements in Perl. We will cover the basics of conditional execution using if-else-if statements.


What is an Else-If statement

An else-if statement is a conditional statement that allows multiple conditions to be tested sequentially. It provides a way to execute different code blocks based on different conditions.


Syntax

The syntax for the else-if statement in Perl is:

if (condition1) {
    # Code block to execute if condition1 is true
} elsif (condition2) {
    # Code block to execute if condition2 is true
} else {
    # Code block to execute if none of the conditions are true
}

The else-if statement evaluates the specified conditions in order. The first condition that is true will have its code block executed; if none of the conditions are true, the code block inside the else statement is executed.

Flowchart of Else-If Statement


Checking if a Number is Positive, Negative, or Zero

  1. Declare a variable num.
  2. Assign a value to num.
  3. Use an if-else-if statement to check if num is positive, negative, or zero.
  4. Print a message indicating whether num is positive, negative, or zero.

Perl Program

my $num = -5;
if ($num > 0) {
    print "$num is positive.\n";
} elsif ($num < 0) {
    print "$num is negative.\n";
} else {
    print "$num is zero.\n";
}

Output

-5 is negative.


Checking the Grade of a Student

  1. Declare a variable marks.
  2. Assign a value to marks.
  3. Use an if-else-if statement to check the grade based on the marks.
  4. Print a message indicating the grade.

Perl Program

my $marks = 85;
if ($marks >= 90) {
    print "Grade: A\n";
} elsif ($marks >= 80) {
    print "Grade: B\n";
} elsif ($marks >= 70) {
    print "Grade: C\n";
} elsif ($marks >= 60) {
    print "Grade: D\n";
} else {
    print "Grade: F\n";
}

Output

Grade: B


Checking the Temperature Range

  1. Declare a variable temperature.
  2. Assign a value to temperature.
  3. Use an if-else-if statement to check the range of the temperature.
  4. Print a message indicating the temperature range.

Perl Program

my $temperature = 75.5;
if ($temperature > 100) {
    print "It's extremely hot.\n";
} elsif ($temperature > 85) {
    print "It's hot.\n";
} elsif ($temperature > 60) {
    print "It's warm.\n";
} elsif ($temperature > 32) {
    print "It's cold.\n";
} else {
    print "It's freezing.\n";
}

Output

It's warm.