PERL Conditional Statements

The conditional statements are if and unless, and they allow you to control the execution of your script. There are five different formats for the if statement:
if (EXPR)
if (EXPR) BLOCK
if (EXPR) BLOCK else BLOCK
if (EXPR) BLOCK elsif (EXPR) BLOCK ...
if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
STATEMENT if (EXPR)
The first format is classed as a simple statement, since it can be used at the end of another statement without requiring a block, as in:
print "Happy Birthday!n" if ($date == $today);
In this instance, the message will only be printed if the expression evaluates to a true value.
The second format is the more familiar conditional statement that you may have come across in other languages:
if ($date == $today)
{
print "Happy Birthday!n";
}
This produces the same result as the previous example.
The third format allows for exceptions. If the expression evaluates to true, then the first block is executed; otherwise (else), the second block is executed:
if ($date == $today)
{
print "Happy Birthday!n";
}
else
{
print "Happy Unbirthday!n";
}
The fourth form allows for additional tests if the first expression does not return true. The elsif can be repeated an infinite number of times to test as many different alternatives as are required:
if ($date == $today)
{
print "Happy Birthday!n";
}
elsif ($date == $christmas)
{
print "Happy Christmas!n";
}
The fifth form allows for both additional tests and a final exception if all the other tests fail:
if ($date == $today)
{
print "Happy Birthday!n";
}
elsif ($date == $christmas)
{
print "Happy Christmas!n";
}else
{
print "Happy Unbirthday!n";
}
The unless statement automatically implies the logical opposite of if, so unless the EXPR is true, execute the block. This means that the statement
print "Happy Unbirthday!n" unless ($date == $today);

is equivalent to

print "Happy Unbirthday!n" if ($date != $today);
For example, the following is a less elegant solution to the preceding if...else. Although it achieves the same result, example:
unless ($date != $today)
{
print "Happy Unbirthday!n";
}
else
{
print "Happy Birthday!n";
}
The final conditional statement is actually an operator.the conditional operator. It is synonymous with the if...else conditional statement but is shorter and more compact. The format for the operator is:
(expression) ? (statement if true) : (statement if false)
For example, we can emulate the previous example as follows:
($date == $today) ? print "Happy B.Day!n" : print "Happy Day!n";

No comments:

Post a Comment