Perl If statement

Perl groups statements into block of code or block. Each block is surrounded by a curly braces. Block can be nested within block.

  1. { #statements here
  2.   { # nested block
  3.     # statements here
  4.   }
  5. }

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:

  1. if(condition){
  2.    statements;
  3. }
If the condition is true the statements inside block will be executed. For example:
  1. $x = 10;
  2. $y = 10;
  3.  
  4. if($x == $y){
  5.   print "$x is equal to $y";
  6. }

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:

  1. if(condition){
  2.    if-statements;
  3. }
  4. else{
  5.    else-statements;
  6. }

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

  1. $x = 5;
  2. $y = 10;
  3.  
  4. if($x == $y){
  5.   print "x is equal to y";
  6. }
  7. else{
  8.   print "x is not equal to y";
  9. }

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

  1. if(condition1){
  2. }
  3. else if(condition2){
  4. }
  5. else if(condition3){
  6. }
  7. ...
  8. else{
  9. }

Here is the source code example

  1. $x = 5;
  2. $y = 10;
  3.  
  4. if($x > $y){
  5.   print "x is greater than y";
  6. }
  7. else if ($x < $y){
  8.   print "x is less than y";
  9. }
  10. else{
  11.   print "x is equal to y";
  12. }

If control structure can be nested within other.

In this tutorial, you've learn how to use If control structure in Perl. You've also learn if-else and if-else-if control structure as well.