无涯教程-Perl - while 语句函数

51 阅读1分钟

只要给定条件为真,Perl编程语言中的 while 循环语句就会重复执行目标语句。

while - 语法

while(condition) {
   statement(s);
}

while - 流程图

while loop in Perl

在这里, while 循环的关键点是该循环可能永远不会运行。当测试条件并且输出为false时,将跳过循环主体,并执行while循环之后的第一条语句。

while - 示例

#!/usr/local/bin/perl
 
$a=10;

# while loop execution
while( $a < 20 ) {
   printf "Value of a: $a\n";
   $a=$a + 1;
}

在这里,我们使用比较运算符<将变量$a的值与20进行比较。因此,虽然$a的值小于20,而while循环继续执行它旁边的代码块,并且一旦$a的值变为 等于20,就出来了 执行后,以上代码产生以下输出-

Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
Value of a: 16
Value of a: 17
Value of a: 18
Value of a: 19

参考链接

www.learnfk.com/perl/perl-w…