Perl IF...ELSIF statement
An if statement can be followed by an optional elsif...else statement, which is very useful to test various conditions using single if...elsif statement.When using if , elsif , else statements there are few points to keep in mind.
·
An if can have zero or one else's and it must
come after any elsif's.
·
An if 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 if...elsif...else statement in Perl programming language is:if(boolean_expression 1){
# Executes when the boolean expression 1 is true
}
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 true
}
Example:
#!/usr/local/bin/perl
$a = 100;
# check the boolean condition using if statement
if( $a == 20 ){
# if condition is true then print the following
printf "a has a value which is 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 true
printf "a has a value which is $a\n";
}
Here we are using 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 returns false. When the above code is executed, it produces following result:
a has a value which is 100
No comments:
Post a Comment