简体   繁体   English

嵌套for循环问题TCL

[英]Nested for loop issue 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
}               

I am not able to enter the second for loop, is this a formatting issue ? 我无法进入第二个for循环,这是格式化问题吗? gives me some weird error. 给了我一些奇怪的错误。 I added the sleep just to check whats happening so ignore that. 我添加睡眠只是为了检查发生了什么,因此请忽略它。

In your code your inner loop is only evaluating if nl >=4 . 在您的代码中,您的内部循环仅在nl >=4评估。 nl will be initialized as 0 from [lindex $z $ml] [lindex $z $ml]中将nl初始化为0

Since you are incrementing $nl, my guess is you should change this line: 由于您要增加$ nl,我想您应该更改此行:

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

to this instead: 改为:

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

Was it perchance something like this you intended? 您打算像这样的东西吗?

# 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
    }
}

Note that I've moved the incr command invocations to the third argument (the next command string, as the documentation puts it) of the for command invocations. 请注意,我搬到了incr命令调用的第三个参数( 下一个命令字符串,如文件所说的那样)的for命令调用。 You can put anything you want to run at the end of each iteration there, including puts commands as you did, but it's a convention and good practice to have the loop-control-changing commands (whatever they may be) there, and not much else. 您可以在每次迭代的末尾放置任何您想运行的东西,包括像您一样puts命令,但是在这里有一个惯例和好的做法是在其中puts更改循环控制的命令(无论它们可能在哪里),并且不要太多其他。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM