Perl continue 語句



在條件即將再次求值之前,總是會執行一個 continue BLOCK。continue 語句可與 whileforeach 迴圈一起使用。continue 語句還可以單獨與一段程式碼 BLOCK 一起使用,在這種情況下,它將被視為一個流程控制語句,而不是一個函式。

語法

使用 while 迴圈的 continue 語句的語法如下所示 −

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

使用 foreach 迴圈的 continue 語句的語法如下所示 −

foreach $a (@listA) {
   statement(s);
} continue {
   statement(s);
}

使用程式碼 BLOCK 的 continue 語句的語法如下所示 −

continue {
   statement(s);
}

例項

以下程式使用 while 迴圈模擬 for 迴圈 −

#/usr/local/bin/perl
   
$a = 0;
while($a < 3) {
   print "Value of a = $a\n";
} continue {
   $a = $a + 1;
}

這將產生以下結果 −

Value of a = 0
Value of a = 1
Value of a = 2

以下程式展示了使用 foreach 迴圈的 continue 語句 −

#/usr/local/bin/perl
   
@list = (1, 2, 3, 4, 5);
foreach $a (@list) {
   print "Value of a = $a\n";
} continue {
   last if $a == 4;
}

這將產生以下結果 −

Value of a = 1
Value of a = 2
Value of a = 3
Value of a = 4
perl_loops.htm
廣告
© . All rights reserved.