0

我有一个带有这个片段的脚本:

 while {[gets $fin line] != -1} {
 if {[string first "Modem :" $line] != -1} {
            set line2 [string range $line 17 end]
            puts $fout "One : \t$line2"
    }

    puts $fout "Two : \t$line2"
 }

工作并打印输出(当One :我不包含Two :脚本中的部分时)但是当我包含时Two :,它显示

error : can't read "line2": no such variable
    while executing
"puts $fout "Two : \t$line2""
    ("while" body line 14)

line2出来后不保值if吗?

4

2 回答 2

1

从聊天中,是一个示例$fin

代码的问题是一次while {[gets $fin line] != -1}循环遍历每一行$fin,而不是一堆在一起。read是在一个变量中获取所有行的命令。

这意味着当读取第一行时,您没有$line1$line2在循环的第一次迭代中,因此puts将无法通过这些名称检索变量。

我提出的解决方案是首先获取每个必需的变量,然后在为“块”收集所有内容后,一次打印它们。

set fin [open imp_info r]
set fout [open imfp_table w]

puts $fout "LINK\tModem Status"
puts $fout "----\t------------"

while {[gets $fin line] != -1} {

        # If there is "wire-pair (X)" in the line, get that number
        regexp -- {wire-pair \(([0-9]+)\)} $line - wire_pair_no

        # Last column, get the value and puts everything
        if {[regexp -- {Modem status: ([^,]+)} $line - status]} {
               puts $fout "$wire_pair_no\t$status"
        }

}

输出:

LINK    Modem Status    
----    ------------
0       UP_DATA_MODE
1       UP_DATA_MODE
于 2014-07-01T14:30:33.973 回答
0

如果您在此循环中阅读第一行:

while {[gets $fin line] != -1} {
    if {[string first "Modem :" $line] != -1} {
        set line2 [string range $line 17 end]
        puts $fout "One : \t$line2"
    }
    puts $fout "Two : \t$line2"
}

你没有“<code>Modem :” 在它的某处,条件不满足,处理if. 以下puts失败是因为该line2变量尚未设置为任何内容;那里没有变量,$语法根本不喜欢那样。

一种可能的解决方法是line2在循环开始之前设置一些东西:

set line2 "DUMMY VALUE"

或者,也许您应该将正在读取的变量更改lineline2.

puts $fout "Two : \t$line"

或者也许你应该在读取变量之前测试它是否存在:

if {[info exists line2]} {
    puts $fout "Two : \t$line2"
}

一切都会奏效,但他们做的事情不同,我不知道你想要什么……</p>

于 2014-07-01T14:11:56.077 回答