Perl Break Statement


Perl Break Statement

In this tutorial, we will learn about the last statement in Perl. We will cover the basics of using the last statement to exit loops prematurely.


What is a Last Statement

A last statement is used to exit a loop prematurely in Perl. When a last statement is encountered, it immediately exits the innermost loop it is in.


Syntax

The syntax for the last statement in Perl is:

last;

The last statement can be used in for, foreach, while, and until loops to exit the loop prematurely.



Exiting a For Loop Early

  1. Use a for loop to iterate from 1 to 10.
  2. Inside the loop, use an if statement to check if $_ is equal to 5.
  3. If the condition is true, use a last statement to exit the loop.
  4. Print the value of $_.

Perl Program

foreach (1..10) {
    if ($_ == 5) {
        last;
    }
    print $_ . " ";
}

Output

1 2 3 4


Exiting a While Loop Early

  1. Declare a variable $i and initialize it to 1.
  2. Use a while loop to iterate while $i is less than or equal to 10.
  3. Inside the loop, use an if statement to check if $i is equal to 5.
  4. If the condition is true, use a last statement to exit the loop.
  5. Print the value of $i.

Perl Program

$i = 1;
while ($i <= 10) {
    if ($i == 5) {
        last;
    }
    print $i . " ";
    $i++;
}

Output

1 2 3 4