2012-07-17 55 views
1

我在while循环中有一个for循环。我有一个条件来打破for循环中的while。在tcl中打破父循环

下面是代码:

while {[gets $thefile line] >= 0} { 
    for {set i 1} {$i<$count_table} {incr i} { 
    if { [regexp "pattern_$i" $line] } { 
     for {set break_lines 1} {$break_lines<$nb_lines} {incr break_lines} { 
     if {[gets $thefile line_$break_lines] < 0} break 
     } 
    } 
    #some other process to do 
} 

我想跳过$nb_lines解析,以进一步做其他事情的文件中。这里中断,打破了for循环,所以它不起作用。

for循环可以使while循环断开吗? 但突破只是为1(或更多)线,我想继续分析该文件的突破工艺线后进一步

感谢

回答

3

break命令(和continue太)不执行多层次退出循环。国际海事组织,最简单的解决方法是只是重构的代码,所以你可以return退出外层循环。不过,如果你不能做到这一点,那么你可以使用这样的事情,而不是(8.5及更高版本):

proc magictrap {code body} { 
    if {$code <= 4} {error "bad magic code"}; # Lower values reserved for Tcl 
    if {[catch {uplevel 1 $body} msg opt] == $code} return 
    return -options $opt $msg 
} 
proc magicthrow code {return -code $code "doesn't matter what this is"} 

while {[gets $thefile line] >= 0} { 
    magictrap 5 { 
     for {set i 1} {$i<$count_table} {incr i} { 
     if { [regexp "pattern_$i" $line] } { 
      for {set break_lines 1} {$break_lines<$nb_lines} {incr break_lines} { 
       if {[gets $thefile line_$break_lines] < 0} {magicthrow 5} 
      } 
     } 
     } 
    } 
    #some other process to do 
} 

5是不是很特别(它只是一个自定义的结果码; Tcl的储量0 -4,但是让其他人保持独立),但是你需要为自己选择一个值,以便它不与程序中的任何其他用途重叠。 (大多数情况下可以重做代码,所以它可以在8.4之前和之前一起使用,但是在那里重新抛出异常会比较复杂。)

请注意,自定义异常代码是“深度魔法”的一部分TCL。 如果可以,请使用普通的重构。

+0

如果你想知道,0是为正常成功,1是为了一个错误(并导致堆栈跟踪建立在展开期间),2用于从当前程序返回,3用于“break”,4用于“continue”。 – 2012-07-17 20:11:31

+0

好的,谢谢! – heyhey 2012-07-18 12:40:20

1

也许是显而易见的,但你可以使用一个额外的变量(go_on )打破,同时:

while {[gets $thefile line] >= 0} { 
    set go_on 1 
    for {set i 1} {$i<$count_table && $go_on} {incr i} { 
    if { [regexp "pattern_$i" $line] } { 
     for {set break_lines 1} {$break_lines<$nb_lines && $go_on} {incr break_lines} { 
     if {[gets $thefile line_$break_lines] < 0} { set go_on 0 } 
     } 
    } 
    } 
    #some other process to do 
} 
+0

嗨,好吧,这可以工作喙。但是这是一个太艰难的突破,我不能继续解析文件,我不能在#点做其他处理。你有想法继续解析吗? (我编辑了一下我的问题) – heyhey 2012-07-17 14:22:15

+0

我不是很清楚你想做什么,但是这可能会起作用 – perreal 2012-07-17 14:31:40

+0

我们已经接近尾声,但并不好。这是我的错,我还不够清楚。我想用解析文件的时候,在解析过程中,我正在寻找不规则的模式(这就是为什么我要做for循环)。当我发现模式,我想跳过线进一步处理线。我想打破只为1(或更多)线,而不是停止解析 – heyhey 2012-07-17 14:41:58