一、for循环
#!/usr/bin/perl
for( $a = 0; $a < 5; $a = $a + 1 ){
print "$a\n";
}
运行结果如下所示
二、while循环
#!/usr/bin/perl
$a = 0;
while( $a < 5 ){
printf "$a\n";
$a = $a + 1;
}
运行结果如下所示
三、foreach循环
#!/usr/bin/perl
@list = (0,1,2,3,4);
foreach $a (@list){
print "$a\n";
}
运行结果如下所示
四、do_while循环
#!/usr/bin/perl
$a = 0;
do{
printf "$a\n";
$a = $a + 1;
}while( $a < 5 );
运行结果如下所示
五、until循环
#!/usr/bin/perl
$a = 0;
until( $a > 4 ){
printf "$a\n";
$a = $a + 1;
}
运行结果如下所示
六、嵌套循环
6.1 while-while
#!/usr/bin/perl
$a = 0;
$b = 0;
while($a < 2){
$b = 0;
while( $b < 2 ){
print "$a, $b\n";
$b = $b + 1;
}
$a = $a + 1;
}
运行结果如下所示
6.2 for-for
#!/usr/bin/perl
for( $a = 0; $a < 2; $a = $a + 1 ){
for( $b = 0; $b < 2; $b = $b + 1 ){
print "$a,$b\n";
}
}
运行结果如下所示
6.3 foreach-foreach
#!/usr/bin/perl
@list = (0, 1);
foreach $a (@list){
foreach $b (@list){
print "$a,$b\n";
}
}
运行结果如下所示
6.4 do..while-do..while
#!/usr/bin/perl
$a = 0;
do{
$b=0;
do{
printf "$a,$b\n";
$b = $b + 1;
}while( $b < 2 );
$a = $a + 1;
}while( $a < 2 );
运行结果如下所示
6.5 until-until
#!/usr/bin/perl
$a = 0;
until( $a > 1 ){
$b = 0;
until( $b > 1 ){
printf "$a,$b\n";
$b = $b + 1;
}
$a = $a + 1;
}
运行结果如下所示
七、next,next 语句将返回到循环体的起始处开始执行下一次循环
#!/usr/bin/perl
$a = 0;
while( $a < 5 ){
if( $a == 3)
{
$a = $a + 1;
next;
}
print "$a\n";
$a = $a + 1;
}
运行结果如下所示
八、 last 语句,退出循环语句块,从而结束循环,last语句之后的语句不再执行
#!/usr/bin/perl
$a = 0;
while( $a < 5 ){
if( $a == 3)
{
$a = $a + 1;
last;
}
print "$a\n";
$a = $a + 1;
}
运行结果如下所示
九、continue语句,通常在条件语句再次判断前执行
#/usr/bin/perl
$a = 0;
while($a < 2){
print "$a\n";
}continue{
$a = $a + 1;
}
运行结果如下所示