Perl 简明教程

Perl Conditional Statements - IF…​ELSE

Perl 条件语句有助于决策制定,它要求程序员指定程序要计算或测试的一个或多个条件,以及如果确定条件为真时执行的语句或语句,并且在确定条件为假时可以选择要执行其他语句。

Perl conditional statements helps in the decision making, which require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

以下是大多数编程语言中典型的决策结构的总体形式 −

Following is the general from of a typical decision making structure found in most of the programming languages −

decision making

数字 0、字符串 '0' 和 ""、空列表 () 和 undef 在布尔上下文中均为 false ,其他所有值均为 true 。通过 !not 对真值取反将返回一个特殊的假值。

The number 0, the strings '0' and "" , the empty list () , and undef are all false in a boolean context and all other values are true. Negation of a true value by ! or not returns a special false value.

Perl 编程语言提供了以下类型的条件语句。

Perl programming language provides the following types of conditional statements.

Sr.No.

Statement & Description

1

if statementAn if statement consists of a boolean expression followed by one or more statements.

2

if…​else statementAn if statement can be followed by an optional else statement.

3

if…​elsif…​else statementAn if statement can be followed by an optional elsif statement and then by an optional else statement.

4

unless statementAn unless statement consists of a boolean expression followed by one or more statements.

5

unless…​else statementAn unless statement can be followed by an optional else statement.

6

unless…​elsif..else statementAn unless statement can be followed by an optional elsif statement and then by an optional else statement.

7

switch statementWith the latest versions of Perl, you can make use of the switch statement. which allows a simple way of comparing a variable value against various conditions.

The ? : Operator

让我们检查 conditional operator ? :*which can be used to replace *if…​else 语句。其具有以下通用形式:

Let’s check the conditional operator ? :*which can be used to replace *if…​else statements. It has the following general form −

Exp1 ? Exp2 : Exp3;

其中 Exp1、Exp2 和 Exp3 是表达式。请注意冒号的用处和位置。

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

一个?表达式的值将以这种方式确定:计算 Exp1。如果为 true,则计算 Exp2 并将其作为整个?表达式的值。如果 Exp1 为 false,则计算 Exp3,并将它的值作为表达式的值。这是一个使用该运算符的简单示例 −

The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. Below is a simple example making use of this operator −

#!/usr/local/bin/perl

$name = "Ali";
$age = 10;

$status = ($age > 60 )? "A senior citizen" : "Not a senior citizen";

print "$name is  - $status\n";

这会产生以下结果 −

This will produce the following result −

Ali is - Not a senior citizen