redo 操作符也用于控制循环,它不经过任何条件测试直接返回到本次循环的顶端,这种概念在 C 语言里并不存在。它和 next 的区别是,next 会正常继续下一次迭代,而 redo 则会重新执行这次迭代。比较下面的程序:
[Perl] 纯文本查看 复制代码 #!/usr/bin/perl
foreach (1..10) {
print "Iteration number $_.\n\n";
print "Please choose: last, next, redo, or none of the above? ";
chomp (my $choice = <STDIN>);
print "\n";
last if $choice =~ /last/i;
next if $choice =~ /next/i;
redo if $choice =~ /redo/i;
print "That wasn't any of the choices... onward~\n\n";
}
print "That's all, folks!\n";
运行输出:# ./redo2.pl
Iteration number 1.
Please choose: last, next, redo, or none of the above? next
Iteration number 2.
Please choose: last, next, redo, or none of the above? next
Iteration number 3.
Please choose: last, next, redo, or none of the above? redo
Iteration number 3.
Please choose: last, next, redo, or none of the above? next
Iteration number 4.
Please choose: last, next, redo, or none of the above? ^C 由输出可见,在使用 redo 时,foreach 停止向前推进,而是在当前所在地重新开始。 |