How to use next to skip to the next iteration in Perl?
Question
How to use next to skip to the next iteration in Perl?
In Perl, the next keyword is used inside loops to immediately skip the rest of the current iteration and jump to the start of the next iteration. It works similarly to continue in other languages. This is useful when you want to conditionally ignore some iterations but keep looping.
Perl has several types of loops such as for (or foreach), while, and until. The next keyword works in all of them.
How next works
- When Perl encounters
nextinside the loop body, it skips the remaining statements for the current iteration. - It then continues with the next loop iteration if the loop condition still holds.
- Used thoughtfully,
nexthelps avoid deeply nestedifstatements and keeps code simpler.
Example: Using next in a foreach loop
This example prints only the even numbers from an array and skips the odd ones using next:
#!/usr/bin/perl
use strict;
use warnings;
my @numbers = (1..10);
foreach my $num (@numbers) {
# Skip odd numbers
if ($num % 2 != 0) {
next;
}
print "$num is even\n";
}
Output:
2 is even 4 is even 6 is even 8 is even 10 is even
Important points about next in Perl
nextonly affects the loop it is in.- You can label loops (e.g.,
OUTER: foreach) and usenext OUTER;to specify which loop to continue when nested. - Using
nextis clearer than deeply nested conditionals for skipping iterations. nextdiffers fromlast, which exits the loop entirely.- Remember to use
use strict;anduse warnings;to catch common errors.
Summary
Use next inside a loop to immediately jump to the next iteration, skipping any code remaining in the current one. This enhances code readability and flow control in your looping constructs.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 7ms
2 is even
4 is even
6 is even
8 is even
10 is even
(empty)