错误:can';“我不读”;第2行“是:tcl中没有这样的变量
我有一个包含以下代码段的脚本:错误:can';“我不读”;第2行“是:tcl中没有这样的变量,tcl,puts,Tcl,Puts,我有一个包含以下代码段的脚本: 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:工作并打印输出(当我在脚本中不包含T
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)
如果你在这个循环中读到的第一行代码是:
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"
}
如果您的调制解调器上没有“调制解调器:
”,则在处理if
时,该条件不满足,且未触及变量。以下put
失败,因为line2
变量尚未设置为任何值;这里没有变量,$
语法根本不喜欢这样
一种可能的修复方法是将line2
设置为循环开始之前的某个值:
set line2 "DUMMY VALUE"
或者您应该将读取的变量更改为line
,而不是line2
puts $fout "Two : \t$line"
或者,您应该在读取变量之前测试它是否存在:
if {[info exists line2]} {
puts $fout "Two : \t$line2"
}
所有这些都会起作用,但它们做不同的事情,我不知道你想要什么…来自聊天,是$fin
的一个示例
代码的问题是,while{[gets$fin line]!=-1}
一次循环一行,而不是一整行read
是在一个变量中获取所有行的命令
这意味着当读取第一行时,循环的第一次迭代中没有$line1
或$line2
,因此,put
将无法按这些名称检索变量
我建议的解决方案是首先获取每个必需的变量,然后在为“块”收集所有内容时,立即打印它们
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
如果
$fin
中的第一行没有子字符串调制解调器:
,那么如果和行2
还不存在,您将无法进入。。。你想做什么?但我肯定,有子串。我看到文件了,是在文件的第一行吗?如果没有,则会出现错误。我正在尝试构建一个表。。通过grep
ing在两个这样的if
语句中查找两个子字符串。然后在if
s之外,我使用put$fout“$line1\t$line2”
很抱歉,我没有收到你上面的第二条评论。可以用跟踪做“聪明”的事情,使明显的变量语义失效。不要那样做。真正地(你不可能在不知情的情况下这么做。)