Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Perl Conditional Statements

Perl Conditional Statements

Perl conditional statements determine which block of code to execute based on the result (True or False) of one or more statements.

The following diagram gives a simple view of how conditional statements execute:

Note that the number 0, the string '0' 、 "" , empty list() , and LinkedHashMap, among others. undef is false , all other values are true. Prefixing true with ! or notreturns false.

Perl provides the following conditional statements:

Statement Description

if statement

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

if...else statement

A if 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 use one if statement can be followed by an optional elsif statement, followed by another else statement。

unless statement

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

unless...else statement.

A unless statement An if statement can be followed by an optional else statement。

unless...elsif..else statement

A unless statement An if statement can be followed by an optional elsif statement, followed by another else statement。

switch statement

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

Ternary operator ? :

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



Exp1 ? Exp2 : Exp3;

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

The example is as follows:

Example

#!/usr/local/bin/perl

$name

=

"

Runoob Tutorial

"

;

$favorite

=

10

;

Like count

$status

=

(

$favorite

60

)

?

"

Popular website

"

:

"

Not a popular website

"

;

print

"

$name

$status

\n

"

;

Running the above program, the output is:



Runoob Tutorial - 不是热门网站