if 语句 TCL

if statement TCL

proc test {} {

set infile [open "infile" r]
set linecount 0

while {[gets $infile line] > 0 {
    incr linecount

    set price [split $line ","]


    if {[reqexp  "Game" $price]} {

       set token [lindex $price end-3]
       set token1 [lindex $price end-2]

    } else {
       if {2 < $linecount < 4} {
       set token [lindex $price end-3]
       set token1 [lindex $price end-2]

       puts "$game"

}
}
}
close $infile

}

我有很多行的输入文件:我希望能够将第 2 行放入第 4 行,但是我放入的 if 语句 (if { 0 < $linecount < 2} 似乎不起作用。你呢?知道如何让脚本输出某些行吗?

Game a b c
1 2 3 4
3 4 5 6
4 5 6 7
3 4 5 6      

与大多数语言一样,但 不像 Python 那样 ,二进制 <= 运算符在这样使用时不会执行您似乎期望的操作。它最终会像写成 (2 <= $linecount) <= 4 一样工作,并且当内部项计算为 0(对于 false)或 1(对于 true)时,外部项始终为 true。

获得所需内容的最简单方法是使用 tcl::mathop::<= 命令,该命令 使用三个参数执行您想要的操作:

# rest of your code as it was...

if {[tcl::mathop::<= 2 $linecount 4]} {

# rest of your code as it was...

如果您无法使用没有该命令的旧版本的 Tcl(或者如果您更喜欢用以下风格编写代码),请改为这样写:

if {2 <= $linecount && $linecount <= 4} {

或(如果您喜欢更多括号):

if {(2 <= $linecount) && ($linecount <= 4)} {