while循环
优质
小牛编辑
146浏览
2023-12-01
只要给定条件为真,Perl编程语言中的while循环语句就会重复执行目标语句。
语法 (Syntax)
Perl编程语言中while循环的语法是 -
while(condition) {
statement(s);
}
这里的statement(s)可以是单个陈述或一个陈述块。 condition可以是任何表达。 当条件为真时,循环迭代。 当条件变为假时,程序控制将立即传递到循环之后的行。
数字0,字符串'0'和“”,空列表()和undef在布尔上下文中都是false ,所有其他值都为true 。 否定真正的价值! 或not返回特殊的假值。
流程图 (Flow Diagram)

这里while循环的关键点是循环可能永远不会运行。 当测试条件并且结果为假时,将跳过循环体并且将执行while循环之后的第一个语句。
例子 (Example)
#!/usr/local/bin/perl
$a = 10;
# while loop execution
while( $a < 20 ) {
printf "Value of a: $a\n";
$a = $a + 1;
}
这里我们使用比较运算符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