【问题标题】:Perl - difference between 'next' and 'continue'?Perl - “下一个”和“继续”之间的区别?
【发布时间】:2021-03-11 16:16:10
【问题描述】:

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

【问题讨论】:

  • 简短回答。 Perl next 类似于 Java 和大多数其他语言的 continue。在循环上使用命名标签。 Perl continue 很少被使用。

标签: perl loops


【解决方案1】:

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

continue 关键字在 given-when 构造中还有另一个含义,即 Perl 的 switch-case。在执行when 块之后,Perl 会自动breaks,因为大多数程序都会这样做。如果您想经历到下一个案例,则必须使用continue。这里,continue 修改了控制流。

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 跳转到循环块的开头。不评估循环条件。

【讨论】:

  • 嗨,你能举个例子来对比 continue 和 next 吗?
  • next“仅在循环中可用”是不正确的。你实际上可以next 跳出非循环块,Perl 不会阻止你;它只是不是很有用对你的代码的读者非常友好。
  • @hobbs 当然,但只有如果块被命名if(1){next} 失败,尽管有一个语法块。 sub foo{next} foo() 失败,尽管有句法块。只有像FOO:{next} 这样的命名块有效。还是我错过了什么?
  • @amon 不必命名,它必须是一个裸块,不属于 if。 for (1..3) { print "a"; { next; print "b" } print "c" } 打印“acacac”而不是“aaa”。
  • 第一个代码块有错别字,我怀疑你说的是while(1) { ..而不是when(1) { ...
【解决方案2】:

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

continue 块中的

语句将针对每次迭代执行,无论循环是否照常执行或循环是否需要通过遇到 next 语句来终止特定迭代。 没有 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    相关资源
    最近更新 更多