
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Break Out of a Loop in Perl
In most programming languages, we can use the "break" keyword to break out of any type of loop. In Perl too, we have the "break" keyword available, but the keyword that is used the most to break out of a loop is the "last" keyword.
The "last" Statement in Perl
The "last" statement is used in Perl loops to exit a loop immediately; it is the equivalent of the "break" statement in C/C++ and Java.
In practice, you often use the "last" statement to exit a loop if one of the conditions is met, for example, you find an array element whose key matches your search key, therefore it is not necessary to examine the other elements.
The "last" statement is typically used in conjunction with a conditional statement, such as "if" or "unless".
In this tutorial, we will two different examples to demonstrate how you can use the "last" keyword in Perl to break out of a loop.
Example 1
Consider the code shown below ?
use strict; print "Enter a string: "; while (<STDIN>) { last if $_ eq "tutorialspoint\n"; print "You entered: $_"; } print "Done for now!\n";
In this example, we used the standard input, and then passed that input as an argument to a "while" loop. Run the file with the command "perl sample.pl" and then enter the string "tutorialspoint" in your terminal; it will produce the following output on the screen ?
Enter a string: tutorialspoint Done for now!
Output
Enter a string: hello You entered: hello
Example 2
Now, let's consider another example of the "last" keyword in a "while" loop.
$var = 1; while ($var < 10) { # terminating the loop if ($var == 7) { $var = $var + 1; last; } print "The value of var is: $var\n"; $var = $var + 1; }
In this code, we are starting a "while" loop, and we are telling the compiler that if the value of the variable becomes equal to "7", then simply terminate the loop.
If we save the file with the name "sample.pl" and then run the command "perl sample.pl", then we will get the following output in the terminal.
Output
The value of var is: 1 The value of var is: 2 The value of var is: 3 The value of var is: 4 The value of var is: 5 The value of var is: 6
Observe that, as soon as the value of the variable becomes "7", the control breaks out of the loop.