login

Perl If Statement

Summary: In this tutorial, you will learn how to use Perl if control structure to write simple logic in code.

Perl groups statements into block of code or block. A block is surrounded by a pair of curly braces and can be nested within a block.

{ #statements here
  { # nested block
    # statements here
  }
}

If control structure is used to execute a block of code based on a condition in Perl program. The syntax of If control structure is as follows:

if(condition){
   statements;
}

If the condition is true the statements inside block will be executed, for example:

 $x = 10;
 $y = 10;

 if($x == $y){
   print "$x is equal to $y";
 }

In the line 1 and 2 we define two variables $x and $y with their values are 10. In line 4 we use If statement to print a message if $x is equal $y. Message is only printed if the expression $x == $y is evaluated to true. In Perl, everything is true except number zero 0, empty string "", zero string "0", and undefined (undef) values.

If you need an alternative choice, Perl provides if-else control structure as follows:

 if(condition){
    if-statements;
 }
 else{
    else-statements;
 }

If the condition is false the else-statements will be executed. Here is the code example:

 $x = 5;
 $y = 10;

 if($x == $y){
   print "x is equal to y";
 }
 else{
   print "x is not equal to y";
 }

Perl also provides if-else-if control structure to make multiple choices based on conditions.

 if(condition1){
 }
 else if(condition2){
 }
 else if(condition3){
 }
 ...
 else{
 }

Here is the source code example:

 $x = 5;
 $y = 10;

 if($x > $y){
   print "x is greater than y";
 }
 else if ($x < $y){
   print "x is less than y";
 }
 else{
   print "x is equal to y";
 }

If control structure can be nested within other.

In this tutorial, you've learned how to use If control structure in Perl. You've also learned how to work with if-else and if-else-if control structure.