Perl 决策结构:if、if-else、嵌套 if、elsif 阶梯、unless 语句详解

在编程中,决策制定与我们在现实生活中的决策过程非常相似。在编写代码时,我们经常需要在特定条件满足时执行特定的代码块。编程语言使用控制语句来根据特定条件控制程序的执行流程。这些语句用于根据程序状态的变化来推进执行流程或进行分支。

#### Perl 中的决策语句:

  • If
  • If – else
  • Nested – If (嵌套 If)
  • if – elsif ladder (if-elsif 阶梯)
  • Unless
  • Unless – else
  • Unless – elsif

if 语句

if 语句与其他编程语言中的用法基本相同。它用于执行基于基本条件的任务。它用于决定是否执行某个特定的语句或语句块,即:如果某个条件为真,则执行该语句块,否则不执行。

语法:

if(condition)
{    
     # code to be executed    
}

注意: 如果在 if 语句中不使用花括号 { },则会导致编译时错误。因此,在 if 语句中必须使用花括号 { }。
流程图:

!image

示例:

Perl


CODEBLOCK_fc8622b4

输出:

Even Number

if – else 语句

if 语句在条件为真时执行代码,但如果条件不为真该怎么办呢?这时 else 语句就派上用场了。它告诉代码当 if 条件为假时该做什么。

语法:

if(condition)
{  
      # code if condition is true  
}
else
{  
      # code if condition is false  
}

流程图:

!image

示例:

Perl


CODEBLOCK_bb336f21

输出:

Odd Number

Nested – if 语句(嵌套 if)

在一个 if 语句内部包含另一个 if 语句被称为嵌套 if。在这种情况下,内部的 if 语句是另一个 if 或 else 语句的目标。当需要满足多个条件,且其中一个条件是父条件的子条件时,可以使用嵌套 if。

语法:

if (condition1) 
{
   # Executes when condition1 is true

   if (condition2) 
   {
      # Executes when condition2 is true
   }
}

流程图:

!image

示例:

Perl


CODEBLOCK_e9f5f31e

输出:

Number is divisible by 2 and 5

If – elsif – else 阶梯语句

在这里,用户可以在多个选项中进行决策。if 语句从上到下执行。一旦控制 if 的某个条件为真,就执行与该条件关联的语句,并跳过阶梯的其余部分。如果所有条件都不为真,则执行最后的 else 语句。

语法:

if(condition1)
{  
           # code to be executed if condition1 is true  
}
elsif(condition2)
{  
           # code to be executed if condition2 is true  
}  
elsif(condition3)
{  
           # code to be executed if condition3 is true  
}  
 ... 
else
{
           # code to be executed if all the conditions are false  
}

流程图:
<img src="https:#write.geeksforgeeks.org/wp-content/uploads/if-else-if-1.png" alt="if-else-if" />if-else-if
示例:

Perl


CODEBLOCK_d350265a

输出:

i is 20

unless 语句

在这种情况下,如果条件为假,则执行语句块。在布尔上下文中,数字 0、空字符串 ""、字符 ‘0‘、空列表 () 和 undef 都被视为假(false),而所有其他值都为真。

语法:

unless(boolean_expression) 
{
   # will execute if the given condition is false
}

流程图:

!image

示例:

Perl


Perl program to illustrate

unless statement

$a = 10;

unless($a != 10)

{

# if condition is false then

# print the following

printf "a is not equal to 10

";

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/43372.html
点赞
0.00 平均评分 (0% 分数) - 0