26

next快速 Perl 问题:当通过一个循环(比如一个 while 循环)时,a和continuecommand有什么区别?我认为两者都只是跳到循环的下一次迭代。

4

2 回答 2

22

continue关键字可以在循环之后使用。块中的代码在下一次迭代之前执行(在评估循环条件之前)。它不影响控制流。continue

my $i = 0;
when (1) {
  print $i, "\n";
}
continue {
  if ($i < 10) {
    $i++;
  } else {
    last;
  }
}

几乎相当于

foreach my $i (0 .. 10){
  print $i, "\n";
}

该关键字在Perl 的-构造continue中还有另一个含义- 。在一个块被执行之后,Perl 会自动执行s,因为大多数程序都是这样做的。如果您想进入一个案例,则必须使用。在这里,修改控制流。givenwhenswitchcasewhenbreakcontinuecontinue

given ("abc") {
  when (/z/) {
    print qq{Found a "z"\n};
    continue;
  }
  when (/a/) {
    print qq{Found a "a"\n};
    continue;
  }
  when (/b/) {
    print qq{Found a "b"\n};
    continue;
  }
}

将打印

Found a "a"
Found a "b"

next关键字仅在循环中可用并导致新的迭代,包括。重新评估循环条件。redo跳转到循环块的开头。不评估循环条件。

于 2012-08-22T21:46:36.143 回答
2

执行下一个语句将跳过执行循环中该特定迭代的其余语句。

continue块中的语句将为每次迭代执行,而不管循环是否照常执行,或者循环是否需要通过遇到下一个语句来终止特定的迭代。没有continue块的示例:

my $x=0;
while($x<10)
{
    if($x%2==0)
    {
        $x++; #incrementing x for next loop when the condition inside the if is satisfied.
        next;
    }
    print($x."\n");
    $x++;  # incrementing x for the next loop 
}       

在上面的示例中,x 的增量需要写入 2 次。但是如果我们使用 continue 语句,它可以保存需要一直执行的语句,我们可以在 continue 循环内只增加一次 x。

my $x=0;
while($x<10)
{
    if($x%2==0)
    {
        next;
    }
    print($x."\n");
}
continue
{
        $x++;
}

两种情况下的输出都是 1,3,5,7,9

于 2021-03-11T08:16:10.323 回答