Perl next operator - for loop and if statement examples

Perl next loop FAQ: Can you demonstrate how to use the Perl next operator in a for loop?

Problem: You're writing code for a Perl loop, and you need to write some logic to skip over the current element in the loop, and move on to the next loop element.

The Perl loop next operator

When you're in a Perl for loop (iterating over an array or hash), and you want to move on to the next element in your array or hash, just use the Perl next operator, like this:

for (@array)
{
  if (SOME_TEST_CONDITION)
  {
    # move on to the next loop element
    next;
  }
  
  # more code here ...
}

More Perl next examples

You can see some decent examples of the Perl next operator in the following code. In the code just before this for loop I had just read all the records of a Perl script into an array named @records, and in the Perl for loop shown below I'm skipping over all the strings I'm not really interested in:

for (@records)
{
  # skip blank lines
  next if /^[ \t]*$/;

  # skip comment lines
  next if /#/;

  # skip printing lines
  next if /print/;
  next if /printf/;
  
  # much more code here ...

}

Perl next operator - Summary

As you can see, you use the Perl next operator to skip to the next element in a Perl for loop, and there are at least two ways to use the next operator, as shown in the examples above: inside an if statement, or before an if statement.

Related - how to break out of a Perl for loop

In a related note, you can break out of a Perl for loop using the Perl last operator, like this:

if (SOME_TEST_CONDITION)
{
  last;
}

The Perl last operator works just like the break operator in other languages, breaking out of the loop when the last operator is encountered. You can read more about the last operator in my Perl for loop break tutorial.