The if statement in Perl language is used to perform operation on the basis of condition. By using if-else statement, you can perform operation either condition is true or false. Perl supports various types of if statements:
The Perl single if statement is used to execute the code if condition is true. The syntax of if statement is given below:
if(expression){ //code to be executed }
Let's see a simple example of Perl language if statement.
$a = 10; if( $a %2==0 ){ printf "Even Number\n"; } }
Here, output is even number as we have given input as 10.
The Perl if-else statement is used to execute a code if condition is true or false. The syntax of if-else statement is given below:
if(expression){ //code to be executed if condition is true }else{ //code to be executed if condition is false }
Let's see the simple example of even and odd number using if-else statement in Perl language.
$a = 10; if( $a %2==0 ){ printf "Even Number\n"; }else{ printf "Odd Number\n"; }
Here, input is an even number and hence output is even.
In this example, we'll take input from user by using standard input (<STDIN>/<>).
print "Enter a Number?\n"; $num = <>; if( $num %2==0 ){ printf "Even Number\n"; }else{ printf "Odd Number\n"; }
In the first output, user has entered number 5 which is odd. Hence the output is odd.
In the second output, user has entered number 4 which is even. Hence the output is even.
The Perl if else-if statement executes one code from multiple conditions. The syntax of if else-if statement is given below:
if(condition1){ //code to be executed if condition1 is true }else if(condition2){ //code to be executed if condition2 is true } else if(condition3){ //code to be executed if condition3 is true } ... else{ //code to be executed if all the conditions are false }
The example of if else-if statement in Perl language is given below.
print "Enter a Number to check grade\n"; $num = <>; if( $num < 0 || $num > 100){ printf "Wrong Number\n"; }elsif($num >= 0 && $num < 50){ printf "Fail\n"; }elsif($num >= 0 && $num < 60){ printf "D Grade\n"; }elsif($num >= 60 && $num < 70){ printf "C Grade\n"; }elsif($num >= 70 && $num < 80){ printf "B Grade\n"; }elsif($num >= 80 && $num < 90){ printf "A Grade\n"; }elsif($num >= 90 && $num <= 100){ printf "A+ Grade\n"; }