Perl | last in loop

last keyword is used to loop control statement which immediately causes the current iteration of the loop to become the last. If a label given, then it comes of the loop by the label.

Syntax:
# Comes out of the current loop.
last

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



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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";

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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 is $sum";
           
         # terminate outer loop
         last Label1;
      }
      $b = $b * 2;
   }
   $a = $a * 2;
}

chevron_right


Output:

Sum is 22


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.