Perl 循环中的last

Perl 循环中的last

last关键字用于循环控制语句,该语句会立即使循环的当前迭代成为最后一次。如果给定了一个标签,那么它就会根据这个标签从循环中出来。

语法:

# Comes out of the current loop.
last

# Comes out of the loop specified by
# MY_LABEL
last MY_LABEL

例子1 :

#!/usr/bin/perl
sum = 0;a = 0;
b = 0;
  
while(1) 
{
  sum = a +b;
a =a + 2;
  
# Condition to end the loop
if(sum>10) 
{
    print "Sum =sum\n";
    print "Exiting the loop\n";
    last;
} 
else
{
    b =b - 1;
}
}
print "Loop ended at Sum > 10\n";

输出

Sum = 11
Exiting the loop
Loop ended at Sum > 10

例2 :

#!/usr/local/bin/perl
  
a = 1;sum = 0;
  
# Outer Loop
Label1: while(a<16) 
{
   b = 1;
     
   # Inner Loop
   Label2: while (b<8)
   {
      sum = sum +b;
      if(a == 8) 
      {
         print "Sum issum";
           
         # terminate outer loop
         last Label1;
      }
      b =b * 2;
   }
   a =a * 2;
}

输出

Sum is 22

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程