Perl Conditional Statements
Perl conditional statements are executed based on the result (True or False) of one or more statements to determine the execution of code blocks.
You can get a simple understanding of the execution process of conditional statements through the following diagram:
>
Note that the number 0
, the string '0'
, ""
, an empty list()
, and undef
are false, and all other values are true. Using ! or not before true returns false.
Perl provides the following conditional statements:
Statement | Description |
---|---|
if statement | An if statement consists of a Boolean expression followed by one or more statements. |
if...else statement | An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. |
if...elsif...else statement | You can have an if statement followed by an optional elsif statement, and then another else statement. |
unless statement | An unless statement consists of a Boolean expression followed by one or more statements. |
unless...else statement | An unless statement can be followed by an optional else statement. |
unless...elsif...else statement | An unless statement can be followed by an optional elsif statement, and then another else statement. |
switch statement | In the latest version of Perl, we can use the switch statement, which executes corresponding code blocks based on different values. |
Ternary Operator ? :
We can use the conditional operator ? : to simplify the if...else statement. The general format is:
Exp1 ? Exp2 : Exp3;
If Exp1 is true, it returns the result of Exp2, otherwise it returns Exp3.
Here is an example:
Example
#!/usr/local/bin/perl
$name = "tutorialpro.org";
$favorite = 10; # Number of likes
$status = ($favorite > 60 )? "Popular Site" : "Not a Popular Site";
print "$name - $status\n";
Executing the above program will output:
tutorialpro.org - Not a Popular Site