unless elsif else statement in perl
In Perl, the unless
statement can also be used with multiple elsif
clauses and an else
clause to create complex conditional statements. The syntax for an unless elsif else
statement is as follows:
unless (condition1) { # code to be executed if condition1 is false } elsif (condition2) { # code to be executed if condition1 is false and condition2 is true } elsif (condition3) { # code to be executed if condition1 and condition2 are false and condition3 is true } ... else { # code to be executed if all conditions are false }
Here is an example to demonstrate how unless elsif else
statement works:
my $number = 15; unless ($number == 10) { print "The number is not 10.\n"; } elsif ($number == 20) { print "The number is 20.\n"; } elsif ($number == 15) { print "The number is 15.\n"; } else { print "The number is neither 10 nor 20 nor 15.\n"; }
In this example, the output will be:
The number is 15.
Because the first condition $number == 10
is false, the second condition $number == 20
is also false, but the third condition $number == 15
is true, so the code inside the block for the third elsif
clause is executed.
If the value of $number
were not 15
, the output would have been different depending on the value of $number
. If $number
were 10
, the output would have been:
The number is not 10.
If $number
were 20
, the output would have been:
The number is 20.
If $number
were any value other than 10
, 15
, or 20
, the output would have been:
The number is neither 10 nor 20 nor 15.
Note that the unless elsif else
statement is similar to the if elsif else
statement, but the condition is inverted. The unless
statement is used when you want to execute code when a condition is false, and the if
statement is used when you want to execute code when a condition is true.