一会儿有条件地我正在读取分配,然后测试变量作为布尔表达式。
假设我正在读取一个文件并想要丢弃注释行。然而下面的内容并没有进入循环。看跌期权永远不会打印。
while {[gets $fp line] >= 0 && [regexp {^#} $line] ==0} {
puts "Got valid data"
}
似乎行的获取分配和它的评估不能处于相同的条件中。 TCL 规格中是否证实了这一点?
当然,这个有效,但我希望在一个语句中执行条件。
while {[gets $fp line] >= 0 } {
if {[regexp {^#} $line] == 0 } {
puts "Got valid data"
}
}
干杯。
根据@glennjackman,逻辑是有缺陷的。
这是一个使用函数读取/过滤输入的简单示例
cat gert.tcl
#!/usr/bin/env tclsh
proc filteredRead {fstream lineVar prune} {
upvar $fstream handle;
upvar $lineVar line;
upvar $prune filter; #skip lines matching this regexp
while {[gets $fstream line] >= 0} {
if {[regexp $prune $line]} {
continue
}
return 1
}
return 0
}
if {$argc == 0} {
puts "Usage: $argv0 <filename> [filter (default is ^#)]"
exit 1
}
set filename [lindex $argv 0]
set filter {^#}; # default filter is comment lines
if {$argc == 2} {
set filter [lindex $argv 1]
}
if {![file readable $filename]} {
puts "Error: File '$filename' does not exist or is not readable."
exit 1
}
set handle [open $filename r]
set line ""
puts "\nfiltering lines matching: \[$filter\]"
while {[filteredRead $handle line $filter]} {
puts "\[$line\]"
}
close $handle
#
#invoke against an simple test file
#
cat input
# i'm a comment, skip me
print me
# i'm also comment, skip me
and me
# skip me
# and me
i will be printed
# i'll be skipped
./gert.tcl input
filtering lines matching: [^#]
[print me ]
[]
[and me]
[]
[i will be printed]
希望这有帮助。