在 Tcl 中(具有基本 I/O 的三种解决方案):
set f [open file]
# 1:
while {[chan gets $f line] >= 0} {
set args [lassign $line word]
puts [list $word {*}[lmap {a b} $args {
set a
}]]
}
chan seek $f 0
# 2:
while {[chan gets $f line] >= 0} {
set args [lassign $line word]
puts [list $word {*}[lmap arg $args {
if {[string match -* $arg]} {
set arg
} else {
continue
}
}]]
}
chan seek $f 0
# 3:
while {[chan gets $f line] >= 0} {
set args [lassign $line word]
puts [list $word {*}[lmap arg $args {
if {[string match -* $arg] && ![string is integer $arg]} {
set arg
} else {
continue
}
}]]
}
chan close $f
第一个解决方案只是选择参数列表中的第 0 个、第 2 个、... 单词,恰好是那些以“-”开头的单词。第二种解决方案查看每个参数并选择以“-”开头的参数。第三种解决方案是对第二种解决方案的临时修改,它拒绝负整数参数。
使用来自Tcllib 的fileutil 可以稍微简化相同的解决方案:
package require fileutil
::fileutil::foreachLine line file {
set args [lassign $line word]
puts [list $word {*}[lmap {a b} $args {
set a
}]]
}
等等
预计到达时间
不用说,其他答案中的解决方案也可以在 Tcl 中使用,例如:
::fileutil::foreachLine line file {
puts [regexp -inline -all {(?:^|-)\w+} $line]
}
文档:
>= (operator),
chan,
continue,
file,
fileutil (package),
if,
lassign,
list,
lmap (for Tcl 8.5),
lmap,
open,
package,
puts,
regexp,
set,
string,
while,
{*} (syntax),
Syntax of Tcl regular expressions
Tcl 字符串匹配的语法:
-
* 匹配零个或多个字符的序列
-
? 匹配单个字符
-
[chars] 匹配由 chars 给出的集合中的单个字符(^ 是否 not 否定;范围可以作为 az 给出)李>
-
\x 匹配字符 x,即使该字符是特殊字符(*?[]\ 之一)