在 TCL/TK 脚本中的迭代期间将元素插入列表

inserting elements into List during Iteration in TCL/TK Scripting

我正在尝试将每个输入整数添加到列表中,然后对其进行排序,但是在迭代过程中我无法将每个整数添加到列表中。

代码:

set l1 {1 2 3 4 5}

for {set i 0} {$i<[llength $l1]} {incr i} {
   set data [gets stdin]
   scan $data "%d" myint

   if $myint<=0 {break} # stop if non positive number is found

   set l1 {$myint} # supposed to add an input element into the list during iteration

}

puts $l1

向列表末尾添加元素很容易;只需使用 lappend 而不是 set:

lappend l1 $myint

稍后对列表进行排序时,请使用 lsort -integer,例如此处使用 puts:

puts [lsort -integer $l1]

lsort 命令对值起作用,而不是像 lappend 这样的变量。)


但是,您似乎正在尝试实际输入最多五个值并对它们进行排序。如果是这样,您最好像这样编写代码:

set l1 {}
for {set i 0} {$i < 5} {incr i} {
    set data [gets stdin]
    if {[eof stdin] || [scan $data "%d" myint] != 1 || $myint <= 0} {
        break
    }
    lappend l1 $myint
}
puts [lsort -integer $l1]

区别在这里?我正在使用一个空的初始列表。我正在测试文件结尾。我正在检查 scan 的结果(以防有人提供非整数)。我正在使用复合表达式。这些都是小事,但它们有助于代码更健壮。