Perl Tutorial Perl References

Perl - Unless-Else Statements



Unless Statement

The Unless statement is used to execute a block of code when the condition is evaluated to be false. When the condition is evaluated to be true, the program will skip the unless-code block.

Syntax

unless(condition) {
  statements;
}

Flow Diagram:

Perl Unless Loop

In the example below, the unless code block is created which executes only when the variable i is divisible by 3.

$i = 15;

unless ($i % 3 != 0){
  print("$i is divisible by 3."); 
}

The output of the above code will be:

15 is divisible by 3.

Unless-else Statement

The else statement can be used with unless statement. It is used to execute block of codes whenever unless condition gives true result.

Syntax

unless(condition){
  statements;
} else {
  statements;
}

Flow Diagram:

Perl Unless-else Loop

In the example below, else statement is used to print a message if the variable i is not divisible by 3.

$i = 16;

unless ($i % 3 != 0) {
  print("$i is divisible by 3."); 
} else {
  print("$i is not divisible by 3."); 
}

The output of the above code will be:

16 is not divisible by 3.

elsif Statement

For adding more conditions, elsif statement in used. The program first checks unless condition. When found true, it checks elsif conditions. If all elsif conditions are found false, then else code block is executed.

Syntax

unless(condition){
  statements;
} elsif(condition) {
  statements;
}
...
...
...
} else {
  statements;
}

Flow Diagram:

Perl Unless-elsif-else Loop

In the example below, elsif statement is used to add more conditions between unless statement and else statement.

$i = 16;

unless ($i < 25) {
  print("$i is greater than 25."); 
} elsif($i <=25 && $i >=10) {
  print("$i lies between 10 and 25."); 
} else {
  print("$i is less than 10."); 
}

The output of the above code will be:

16 lies between 10 and 25.