1. Perl
  2. Syntax
  3. here

next statement - jumps to the beginning of the next loop

You can use next statement to jump to the beginning of the next loop.

next

next statement can be used in loop syntax such as while statement, for statement, foreach statement.

while (1) {
  if ($condition) {
    next;
  }
}

for (my $i = 0; $i < 10; $i++) {
  if ($condition) {
    next;
  }
}

foreach my $animal (@animals) {
  if ($condition) {
    next;
  }
}

next statement is used when you want to skip rest statement.

Example program

This is an example program that uses next statement.

Jump to the beginning of the loop when a specific character is matched

In the middle of loop block, you can use next statement when you want to jump to the beginning of the next loop with if statement.

use strict;
use warnings;

my @chars = qw(z z a b c d e f);

for my $char (@chars) {
  next if $char eq 'z';
  print "$char\n";
}

Output:

Only when $char is "z", the program jumps to the beginning of the next loop. print function in the next line is not executed.

a
b
c
d
e
f

qw(z z a b c d e f) is string list operator.

The details of if statement, for statement, and while statement are explained below.

next statement with regular expression

I often use next with regular expression. The following example is that if the string doesn't contain "ABC", the program jumps to the beginning of the next loop.

use strict;
use warnings;

my @strings = ('ABC', 'ABCD', 'CDE', 'FGH');

for my $string (@strings) {
  next unless $string =~ /ABC/;
  print "$string\n";
}

This is the output result. Only those that include "ABC" are output.

ABC
ABCD

last statement - finish the loop

last statement is the syntax associated with next statement . You can finish the loop using last statement.

last

For last statement, See the following article.

Related Informatrion