Getting started...login
Getting started with Perl
author:php.cn  update time:2022-04-14 16:05:12

Perl conditional statements


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 the conditional statement through the following figure:

Note that the number 0, the string '0', "" , empty list (), and undef are false, and other values ​​are true. If true is preceded by ! or not, false will be returned.

Perl provides drop-down conditional statements:

StatementDescription

if statement

An if statement consists of a Boolean expression followed by one or more statements.

if...else statement

A if statement can be followed by an optional else Statement , else statement is executed when the Boolean expression is false.

if...elsif...else statement

You can follow an if statement with An optional elsif statement , followed by 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 may be followed by an optional else statement.

unless...elsif..else statement

An unless statement can be followed by an optional elsif statement , followed by another else statement .

switch statement

In the latest version of Perl, we can use the switch statement. It executes corresponding code blocks based on different values.

Ternary operator? :

We can use conditional operator? : to simplify if. ..else statement operation. The usual format is:

Exp1 ? Exp2 : Exp3;

If the Exp1 expression is true, the Exp2 expression calculation result is returned, otherwise Exp3 is returned.

The example is as follows:

#!/usr/local/bin/perl
 
$name = "php中文网";
$favorite = 10;     # 喜欢数

$status = ($favorite > 60 )? "热门网站" : "不是热门网站";

print "$name - $status\n";

Execute the above program, the output result is:

php中文网 - 不是热门网站

php.cn