【问题标题】:Breaking parent loop in tcl在 tcl 中打破父循环
【发布时间】:2012-07-16 10:18:31
【问题描述】:

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

代码如下:

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 以进一步做其他事情。这里的break,打破了for循环,所以它不起作用。

for 循环可以破坏 while 循环吗? 但是中断仅针对 1 行(或更多)行,我想在中断后继续解析文件以进一步处理行

谢谢

【问题讨论】:

    标签: for-loop while-loop tcl


    【解决方案1】:

    break 命令(和continue 也是)不执行多级循环退出。 IMO,最简单的解决方法就是重构代码,这样您就可以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 代表正常成功,1 代表错误(并导致在展开期间构建堆栈跟踪),2 代表 returning 从当前过程,3 用于break,4 用于continue
    【解决方案2】:

    也许很明显,但您可以使用额外的变量 (go_on) 来中断 while:

    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
    }
    

    【讨论】:

    • 嗨,好的,这可以暂时中断。但这太难了,我无法继续解析文件,也无法在#点进行其他处理。您有继续解析的想法吗? (我已经编辑了一点我的问题)
    • 我不太清楚你想做什么,但这可能会起作用
    • 我们已接近尾声,但情况并不好。这是我的错,我不够清楚。我想用while来解析一个文件,在解析过程中,我正在寻找非常规的模式(这就是我做for循环的原因)。当我找到模式时,我想跳过行以进一步处理行。我想只为 1 行(或更多)行而中断,但不要停止解析
    猜你喜欢
    • 2018-05-05
    • 1970-01-01
    • 2021-03-11
    • 2018-02-28
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多