1. Perl
  2. Syntax
  3. here

next statement - Jump to the beginning of the next iteration [Link transfer]

You can use next statement to jump to the beginning of the next iteration. This corresponds to continue statement in C or Java.

next

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

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

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

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

You can use next statement when you want to skip the process only under specific conditions.

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 processing, you can use next statement when you want to jump to the beginning of the next loop under certain conditions.

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";
}

This is the execution result. Only when it is "z", it jumps to the beginning of the next loop, so the following print function is not executed.

a
b b
c
d
e
f

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

if statement, for statement, and while statement are explained in detail below, so please refer to them.

Try using it with a regular expression

I often combine next with a regular expression. Let's write one example. Let's write an example that skips the output if it doesn't contain the string "ABC". unless statement is used for condition judgment.

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

Related information

You can escape the loop using last statement

Similar to next statement is last statement. You can break out of the loop with last statement.

last

For last statement, refer to the following article.

Related Informatrion