Perl 的 do...while 迴圈



與在迴圈開頭測試迴圈條件的 forwhile 迴圈不同,do...while 迴圈會在迴圈的底部檢查其條件。

do...while 迴圈與 while 迴圈類似,但 do...while 迴圈保證至少執行一次。

語法

Perl 中的 do...while 迴圈的語法如下 −

do {
   statement(s);
}while( condition );

需要注意的是,條件表示式出現在迴圈的末尾,因此迴圈中的語句會在測試條件之前執行一次。如果條件為真,則控制流會跳回到 do,並且迴圈中的語句會再次執行。此過程會一直重複,直到給定的條件變為假。

在布林上下文中,數字 0、字串 '0' 和 "" 、空列表 () 和 undef 都是 ,所有其他值都是 。使用 !not 對真值求反會返回一個特殊的假值。

流程圖

Perl do...while loop

例項

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

# do...while loop execution
do{
   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
perl_loops.htm
廣告
© . All rights reserved.