Perl if-else Statement

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:

  • If-else
  • If else-if
  • Perl If Example

    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

    Flowchart of if statement in Perl

    Let's see a simple example of Perl language if statement.

    $a = 10; if( $a %2==0 ){ printf "Even Number\n";

    Output:

    Even Number
    

    Here, output is even number as we have given input as 10.

    Perl If-else Example

    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

    Flowchart of if-else statement in Perl

    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";

    Output:

    Even Number
    

    Here, input is an even number and hence output is even.

    Perl If-else Example with Input from user

    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";

    Output:

    Enter a Number?
    Odd Number
    
    Enter a Number?
    Even Number
    

    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.

    Perl If else-if Example

    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

    Flowchart of if else-if statement in Perl

    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";

    Output:

    Enter a Number to check grade
    C Grade
    
    Enter a Number to check grade
    Wrong Number
    Next TopicPerl Switch