Perl 語言允許在一個循環內使用另一個循環,下面示範幾個實例來說明這個概念。
巢狀for 迴圈語句的語法:
for ( init ; condition ; increment ) { for ( init ; condition ; increment ) { statement ( s ) ; } statement ( s ) ; }嵌套while 迴圈語句的語法:
while ( condition ) { while ( condition ) { statement ( s ) ; } statement ( s ) ; }嵌套do...while 迴圈語句的語法:
do { statement ( s ) ; do { statement ( s ) ; } while ( condition ) ; } while ( condition ) ;嵌套until 循環語句的語法:
until ( condition ) { until ( condition ) { statement ( s ) ; } statement ( s ) ; }嵌套foreach 迴圈語句的語法:
foreach $a ( @listA ) { foreach $b ( @listB ) { statement ( s ) ; } statement ( s ) ; }執行以上程序,輸出結果為:
a = 0, b = 0a = 0, b = 1a = 0, b = 2a = 1a = 1, b = 0a = 1, b = 1a = 1, b = 2a = 2a = 2, b = 0a = 2, b = 1a = 2, b = 2a = 3