A Perl conditional statement is a block of code that is executed based on the execution result (True or False) of one or more statements.
You can simply understand the execution process of conditional statements through the following figure:
Note that the number 0, string '0', "", empty list (), and undef are false , and all other values are true . If true is used before ! or not , false will be returned.
Perl provides drop-down conditional statements:
statement | describe |
---|---|
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 is executed when the Boolean expression is false. |
if...elsif...else statement | You can follow an if statement with 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 by another else statement . |
switch statement | In the latest versions of Perl, we can use switch statements. It executes corresponding code blocks based on different values. |
We can use the conditional operation?: to simplify the operation of if...else statements. The usual format is:
Exp1 ? Exp2 : Exp3;
If the Exp1 expression is true, the result of the Exp2 expression evaluation is returned, otherwise Exp3 is returned.
An example is shown below:
Executing the above program, the output result is:
Tutorial for code farmers - not a popular website