Perl Conditional Statement

Perl, like all other programming languages, is equipped with specific statements that allow us to check a
condition and execute certain parts of code depending on whether the condition is true or false. Such statements are called conditional statements.



In Perl, there are following forms of conditional statements:
1) If-else
2) Unless

If-else
  1. The if-else statement allows us to select between two alternatives. i.e. either if or else.
  2. Condition is an expression of type boolean, i.e., a conditional expression that is evaluated to true or false
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#!/usr/bin/perl
my $num =50;
if($num>45){
 print "Number is greater than 50";
}elsif($num<50){  
 print "Number is smaller than 50";
}elsif($num==50){  
 print "Number = 50";
}else{  
 print "Invalid";  
}  
print "\n";
Output: Number is greater than 50

Unless
If the Boolean expression evaluates to false, then the block of code inside the unless statement will be executed. 

1
2
3
4
5
6
7
8
$a = 100;
unless( $a == 20 ) {
   #block will execute if the given condition is false
   print "Executing unless as given condition is false\n"; 
} else { 
   print "Executing else as given condition is true\n";
}
print "value of a is: $a\n";
Output: Executing unless as given condition is false.
value of a is: 100

Switch-Case
switch case is deprecated in Perl 5.



<-- Previous || Next -->

1 comment: