Perl Tutorial Perl References

Perl - Last Statement



The last statement in Perl is used to terminate the program out of the loop containing it whenever the condition is met.

If the last statement is used in a nested loop (loop inside loop), it will terminate innermost loop after fulfilling the criteria.

Last statement with While loop

In the example below, the last statement is used to get out of the while loop if the value of variable j becomes 4.

$j = 0;
while ($j < 6){
  $j++;
  if($j == 4){
    print("Getting out of the loop.\n"); 
    last;
  }
  print("$j \n"); 
}

The output of the above code will be:

1
2
3
Getting out of the loop.

Last statement with For loop

Here, the last statement is used to get out of the for loop if the value of variable i becomes 4.

for ($i = 1; $i <= 6; $i++){
  if($i == 4) {
    print("Getting out of the loop.\n"); 
    last;
  }
  print("$i \n");  
}

The output of the above code will be:

1
2
3
Getting out of the loop.

Last statement with Nested loop

The Last statement terminates the inner loop whenever condition is fulfilled. In below mentioned example, program terminates the inner loop only when j = 100 (resulting the program to skip the inner loop for j = 100 and 1000).

#Nested loop without last statement
print("# Nested loop without last statement\n"); 
for ($i = 1; $i <= 3; $i++){
  for ($j = 10; $j <= 1000; $j = $j * 10) {
    print( $i*$j ,"\n"); 
  }
}

The output of the above code will be:

# Nested loop without last statement
10
100
1000
20
200
2000
30
300
3000

#Nested loop with last statement
print("# Nested loop with last statement\n"); 
for ($i = 1; $i <= 3; $i++){
  for ($j = 10; $j <= 1000; $j = $j * 10) {
    if($j == 100){
      last;
    }
    print( $i*$j ,"\n"); 
  }
}

The output of the above code will be:

# Nested loop with last statement
10
20
30

5