Perl UNLESS...ELSIF statement



An unless statement can be followed by an optional elsif...else statement, which is very useful to test the various conditions using single unless...elsif statement.

When using unless, elsif, else statements there are few points to keep in mind.

  • An unless can have zero or one else's and it must come after any elsif's.

  • An unless can have zero to many elsif's and they must come before the else.

  • Once an elsif succeeds, none of the remaining elsif's or else's will be tested.

Syntax

The syntax of an unless...elsif...else statement in Perl programming language is −

unless(boolean_expression 1) {
   # Executes when the boolean expression 1 is false
} elsif( boolean_expression 2) {
   # Executes when the boolean expression 2 is true
} elsif( boolean_expression 3) {
   # Executes when the boolean expression 3 is true
} else {
   # Executes when the none of the above condition is met
}

Example

#!/usr/local/bin/perl
 
$a = 20;
# check the boolean condition using if statement
unless( $a  ==  30 ) {
   # if condition is false then print the following
   printf "a has a value which is not 20\n";
} elsif( $a ==  30 ) {
   # if condition is true then print the following
   printf "a has a value which is 30\n";
} else {
   # if none of the above conditions is met
   printf "a has a value which is $a\n";
}

Here we are using the equality operator == which is used to check if two operands are equal or not. If both the operands are same then it returns true, otherwise it retruns false. When the above code is executed, it produces the following result −

a has a value which is not 20
perl_conditions.htm
Advertisements