while 循环中 continue 的奇怪行为
我对 TCL 编程相当陌生,通过基础知识,我遇到了以下代码片段:
set x 0;
while "$x < 3" {
set x [expr $x + 1]
if {$x >6} break;
if "$x > 2" continue;
puts "x is $x";
}
puts "exited second loop with X equal to $x\n"
执行时,结果如下:
x 是 1
x 是 2
退出第二个循环,X 等于 7
令我惊讶的是,当执行 continue 命令时, while 循环测试 (x<3) 似乎没有被评估。然而,在 tcl 手册页中,“正文中的 continue 语句将停止代码的执行,并且将重新评估测试。”
我错过了什么?
I'm fairly new in TCL programming and by going through the basics I encountered the following code snippet:
set x 0;
while "$x < 3" {
set x [expr $x + 1]
if {$x >6} break;
if "$x > 2" continue;
puts "x is $x";
}
puts "exited second loop with X equal to $x\n"
When executed, the result is the following:
x is 1
x is 2
exited second loop with X equal to 7
What surprises me is that when the continue command is executed the while loop test (x<3) doesn't seem to be evaluated. However in the tcl manpages state that "A continue statement within body will stop the execution of the code and the test will be re-evaluated."
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为您在“$x < 3”中使用了引号,所以您只评估该条件一次:tcl 解释器第一次看到它时,永久地使测试为“0 < 3”。由于它始终为真,因此只有在 [break] 时才退出 while 循环体。
如果您在 while 条件中使用大括号 {} 而不是引号 " ",则该测试仅由 while 循环本身进行评估,而不是由 tcl 解释器的替换传递进行评估,并且按您的预期执行。
经验法则:在 if/while/for 等测试中始终使用 {} (除非第一个提到的行为就是您正在寻找的行为)。
Because you have used quotes in "$x < 3", you are evaluating that condition only once: the first time it is seen by the tcl interpreter, permanently making the test "0 < 3". Since it's always true, you only exit the body of the while loop when you [break].
if you use braces {} instead of quotes " " for the while condition, that test is evaluated only by the while loop itself, and not by the substitution pass of the tcl interpreter, and performs as you would expect.
Rule of thumb: always use {} in the test of if/while/for etc (unless the first mentioned behavior is what you are looking for).