Perl if Menu:
1. if used as a modifier
2. General if statement
2.1. A simple if statement
2.2. if-else
2.3. if-elsif-else
In this short free tutorial, I’ll show you how you can use the Perl if statement in your Perl scripts. The if statement let you execute a block of statements between two curly braces if a boolean condition is evaluated true, otherwise the execution continues with the following block, either an elsif/else block or after the end of the if statement.
You may scope some of your variables with my keyword in the control condition and in this case the scope of the variables extends from its declaration through the rest of the Perl if statement, including any elsif or else clause.
We have two syntax forms for this conditional statement.
In this first form we used if as a modifier of a statement. EXPR represents a condition which must be evaluate in order to execute the Perl if statement.
By writing code like this, you can put the important part of the statement at the beginning, in order to monitor it. The next code sample shows you how to use it when you need to print the values of certain variables in order to debug your Perl script:
$debug = 1;
$a = 1; $b = 2;
# … some statements here
print "a = $a\n" if $debug; # check the $a value
# … other statements
print "b = $b\n" if $debug; # check the $b value
# the rest of script statements
If we want to print the debug messages, at the beginning of the script we set the $debug variable value to 1, otherwise we set it to 0. The next example will show you how to use the regular expressions in the Perl if condition (the =~ operator):
$v = "An example with the if modifier";
print "\\\\$v contains the word \'example\'\n" if ($v =~ /example/);
# it prints: $v contains the word 'example'
$v = "";
This code will execute the print statement only if the $v string variable matches the 'example' word. If it doesn’t, the script will continue with the next statement (i.e. $v = "").
The second syntax form is more general:
if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
where: - EXPR represents a Boolean conditional expression
- the elsif and else clauses are optional and are used if you want to check a certain sequence of conditional expressions and find out which one of them is true
- BLOCK consists of one or more statements enclosed in curly braces; in the construction of a block, the curly braces are always required.
We can split the general conditional Perl if statement as follows:
Perl will evaluate the EXPR and if it is true, it will execute the code between the curly braces of the block. Otherwise, the script will continue with the next statement after the block. Neither elsif nor else clauses are used in the above format. See the next snippet code example:$a = -1;
if($a < 0) {
$a += 2;
}
print "a = $a\n"; # it outputs a = 1
The Perl interpreter will check the condition between parentheses and if the result is true, it will increment the $a scalar variable value with 2.It is possible that EXPR doesn’t represent a condition, like in the following example:
Because the expression is true, the Perl interpreter will continue with the execution of the block, i.e. it will assign the value 1 to the $a scalar variable. As you guess, in this example you don’t need to use the Perl if statement at all, the assign statement $a = 1 is sufficient to do the job.
if (EXPR) BLOCK else BLOCK
The Perl interpreter will evaluate the conditional expression and if the result is true, the execution of the script will continue with the block that follows the conditional expression; otherwise, the script execution will skip inside the block that is after the else clause.Let’s look at a simple example where we need to find the maximum of two numbers:
$a = 15;
$b = 27;
if($a > $b) {
print "max($a, $b) = $a\n";
} else {
print "max($a, $b) = $b\n";
}
# it prints: max(15, 27) = 27
Well, there is a shorter way to do this by using the (?) logical ternary operator - also called the conditional operator. I remind you briefly that the ternary operator (named ternary because it uses three operands) is like an if-else compound statement both included into an expression. Please note that this operator is an expression that returns a value based on the conditional sentence it evaluates. It can be used by following the syntax:
EXPR ? true-value : false-value
The logical ternary operator evaluates its first argument (EXPR) and if this is true, it returns the second argument (true-value), otherwise it returns the third argument (false-value).With the ternary operator, we can rewrite the above code like so:
$a = 15; $b = 27;
print "max($a, $b) = ", $a > $b ? $a : $b,"\n";
The output obtained after running this code will be the same as in the previous example, where we used Perl if statement.Now I’ll discuss a bit about the case when in a Perl if statement we have an empty block after the expression, like in the following snippet code example:
$a = 12; $b = -25;
if($a*$b >= 0 && $a + $b >= 0) {
# do nothing
} else {
print "at least $a or $b is negative\n";
}
There are at least two ways to get rid of the empty if block. One way is to use the Perl unless statement instead of the Perl if statement:$a = 12; $b = -25;
unless($a*$b >= 0 && $a + $b >= 0) {
print "at least $a or $b is negative\\n";
}
In writing the conditional statements, you can swap as you wish between Perl if and Perl unless in order to make your code more readable.Another way is to rewrite the conditional expression enclosed between the parentheses that follow the if keyword: ($a*$b >= 0 && $a + $b >= 0). This is a boolean expression and as you expect Perl provides you with the logical AND operator (&&) and the logical OR operator (||) in order to manipulate the boolean expressions. When you use the && and || operators be careful not to include any spaces between the symbols ("& &" or "| |" is wrong) because you’ll get something you couldn’t expect.
So than we can rewrite the above condition in order to get rid of the empty block:
$a = 12; $b = -25;
if($a*$b < 0) {
print "at least $a or $b is negative\n";
}
if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
This form uses the elsif clause that allows you to check as many conditional expressions as are required. The else clause from the end of the form is still optional but you can use it at the end of the if statement if all other tests fail – with other words, the block of the final else will be executed if none of the conditions are true. The next snippet code shows you an example about how to use if in connection with the elsif and else clauses:
chomp ($line = <STDIN>);
$line = lc($line);
if($line eq "index"){
print "index function\n";
} elsif ($line eq "chomp") {
print "chomp function\n";
} elsif ($line eq "hex") {
print "hex function\n";
} elsif ($line eq "substr") {
print "substr function\n";
} else {
print "$line: unknown function\n";
}
In this example we read a line from <STDIN>, remove the last newline with the chomp function and convert all the characters in lowercases. Next we check if the text read from <STDIN> represents the name of index, chomp, hex or substr functions. If we don’t find any occurrence, the script program will execute the block that follows the else clause.Please note that the Perl interpreter must evaluate all the elsif alternatives you provide in an if statement. If there are too many, you need to reconsider a more efficient way to write the code, like emulate a case or switch statement (in Perl 5.10 you can use the given function).
NEW!!!
Do you want more information about the basic Perl topics?
Check my new "Perl How To" Tutorial eBooks page where I'll answer the most frequent questions regarding some topics :