嵌套for循环问题TCL

时间:2014-01-19 02:28:56

标签: loops for-loop nested tcl

#!/bin/sh
# This is a trial program

puts "++++++++++++++++++++++++++++++++++++++++++++++++++"
set y "0.0.0.0"

set z [split $y "."]
puts "z=$z"
lreplace $z 0 5
puts "z $z"
set v [llength $z]
puts "length of array=  $v"
puts "in the loop-------->\n"
puts " "
incr v -1
puts $v
for {set ml $v } { $ml >= 0} { puts "$ml =ml"} {
    for { set nl [lindex $z $ml]} { $nl >=4} { puts "$nl=nl"} {
        puts $nl
        after 2000
        lset z  $ml $nl
        incr $nl
    }
    after 2000
    incr ml -1
}               

我无法进入第二个for循环,这是格式化问题吗? 给了我一些奇怪的错误。我加入睡眠只是为了检查发生了什么,所以忽略它。

2 个答案:

答案 0 :(得分:2)

在您的代码中,您的内部循环仅评估nl >=4。 nl将从[lindex $z $ml]

初始化为0

由于你增加$ nl,我猜你应该改变这一行:

for { set nl [lindex $z $ml]} { $nl >=4} { puts "$nl=nl"} {

改为:

for { set nl [lindex $z $ml]} { $nl <=4} { puts "$nl=nl"} {

答案 1 :(得分:2)

你想要的是这样吗?

# This is a trial program

puts "++++++++++++++++++++++++++++++++++++++++++++++++++"
set y "0.0.0.0"

set z [split $y "."]
puts "\$z=$z"
set v [llength $z]
# the term 'array' means associative array in Tcl, better use 'list'
puts "length of list=  $v"
puts "in the loop-------->\n\n"
incr v -1
puts "\$v=$v"
for {set ml $v} {$ml >= 0} {incr ml -1} {
    for {set nl [lindex $z $ml]} {$nl <= 4} {incr nl} {
        lset z $ml $nl
        puts $z
    }
}

请注意,我已将incr命令调用移动到for命令调用的第三个参数( next 命令字符串,如文档所述)。您可以在每次迭代结束时放置您想要运行的任何内容,包括puts命令,但是在那里使用循环控制更改命令(无论它们是什么)是一种惯例和良好做法,而不是其他。