Perl Tutorial Perl References

Perl - Given Statement



Like Switch expression in C++ or Java, Perl has given expression which has same functionality. It is used to execute one of many code statements. It can be considered as group of If-else statements.

Syntax

given (expression){
  when (1) {statement 1;}
  when (2) {statement 2;}
     ...
     ...
     ...
  when (N) {statement N;}
  default  {default statement;}
} 

The Given expression is evaluated and matched with the when cases. When it matches, the following block of code is executed.

Example:

In the example below, the given expression is a variable called i with value 2 which is matched against when cases. If a match is found, the following block of code is executed.

use feature qw(switch);  
no warnings 'experimental';

$i = 2;
 
given($i){
 when (1) {print("Red");} 
 when (2) {print("Blue");}
 when (3) {print("Green");}
}

The output of the above code will be:

Blue

default statement

Default Statement is executed when there is no match between given expression and when cases.

Example:

In the example below, the given expression is a variable called i with value 10 which is matched against when cases. As there is no match, hence default block of code gets executed.

use feature qw(switch);  
no warnings 'experimental';

$i = 10;
 
given($i){
 when (1) {print("Red");} 
 when (2) {print("Blue");}
 when (3) {print("Green");}
 default {print("No match found.");}
}

The output of the above code will be:

No match found.

Common code blocks

There are instances where same code block is required in multiple when statements.

Example:

In the example below, same code block is shared for different when cases.

use feature qw(switch);  
no warnings 'experimental';

$i = 10;
 
given($i){
 when (1) {print("Red");} 
 when (2, 10) {print("Blue");}
 when (3, 4, 5) {print("Green");}
 default {print("No match found.");}
}

The output of the above code will be:

Blue

using condition in when statement

Perl gives the flexibility of defining condition in the when expression. It can be achieved bu using topic variable $_.

Example:

In the example below, conditions are defined in second and third when statements to match with a ranges of numbers.

use feature qw(switch);  
no warnings 'experimental';

$i = 50;
 
given($i){
 when (1) {print("Red");} 
 when ($_ > 1 && $_ < 10) {print("Blue");}
 when ($_ >= 10) {print("Green");}
 default {print("No match found.");}
}

The output of the above code will be:

Green

5