The if…else Statement
This statement uses a relational expression to check the validity of a condition and execute a set of statements enclosed in braces. It returns a Boolean value, true or false, according to the validity of the condition. The syntax of the if…else statement is:
if(condition) { block of statement(s); } else { block of statement(s); }
In this syntax, condition is a relational expression. If the result of this expression is true, then the block of statements following the if statement is executed. Otherwise, the block of statements following the else statement is executed.
In Perl, unlike other languages, all loops and conditional constructs require statements to be enclosed in braces, even for single statements.
#! /usr/bin/perl print "Enter a value for a: "; $a = ; print "Enter a value for b: "; $b = ; if ($a>$b) { print "a is greater than bn"; } else { print "b is greater than an"; }
In this example, the if clause checks whether $a is greater than $b. If the value of $a is greater than $b, then the result is: a is greater than b. Otherwise, the control transfers to the code following the else clause and the statement associated with the else clause is printed as a result.
The if…elsif…else Statement
This statement is used when there is more than one condition to be checked. The syntax of the if…elsif…else statement is:
if (condition) { block of statement(s); } elsif (condition) { block of statement(s); } else { block of statement(s); }
In this syntax, if the condition associated with the if clause is false, the control transfers to elsif clause that checks for the next condition. The code associated with elsif clause is executed only if the condition is true or the code associated with the else clause is executed.
#! /usr/bin/perl print "Enter the score of a student: "; $score = ; if($score>=90) { print "Excellent Performancen"; } elsif($score>=70 && $score<90) { print "Good Performancen"; } else { print "Try hardn"; }