Perl 简明教程
Perl Conditional Statements - IF…ELSE
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.
以下是大多数编程语言中典型的决策结构的总体形式 −
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 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
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 是表达式。请注意冒号的用处和位置。
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";
这会产生以下结果 −
Ali is - Not a senior citizen