来自 foreach 循环的意外复合结果
Unexpected compound result from a foreach loop
以下代码片段正在处理 UTF8 编码的文本文件(为医院数据构建 HL7 段,仅供参考):
set linecounter 0
set newmsg ""
foreach line [split $data \n] {
incr linecounter
set seg [append "OBX|" $linecounter "|" [string trimright $line] "||||||V" \n]
lappend newmsg $seg
}
echo "This is the new message: " $newmsg
如果我回显循环内的每个 $seg
,我会得到文本文件中的每一行,就像这样(当然是文件内容):
line1
line2
line3
etc...
然而,一旦完成循环,$newmsg
将显示为:
line1
line1
line2
line1
line2
line3
etc...
我在循环内将lappend
更改为append
,在循环内将其附加到$newmsg
后将set $seg
更改为""
,全部为no有用。想法?
我想,您正在寻找这样的东西:
set data "hello\nworld\nits\nme\nalex"
set linecounter 0
set newmsg ""
foreach line [split $data \n] {
incr linecounter
set seg "OBX|$linecounter|[string trimright $line]||||||V\n"
append newmsg $seg
}
puts "This is the new message: $newmsg"
这将创建其中包含 \n 换行符的字符串。
此代码的示例输出:
This is the new message: OBX|1|hello||||||V
OBX|2|world||||||V
OBX|3|its||||||V
OBX|4|me||||||V
OBX|5|alex||||||V
你得到奇怪的输出有两个原因:
1. append 需要变量名作为第一个参数。所以OBX|是它的名字,它的内容是在循环过程中增长的。
2. 回显列表用于用 {}
包装其项目
以下代码片段正在处理 UTF8 编码的文本文件(为医院数据构建 HL7 段,仅供参考):
set linecounter 0
set newmsg ""
foreach line [split $data \n] {
incr linecounter
set seg [append "OBX|" $linecounter "|" [string trimright $line] "||||||V" \n]
lappend newmsg $seg
}
echo "This is the new message: " $newmsg
如果我回显循环内的每个 $seg
,我会得到文本文件中的每一行,就像这样(当然是文件内容):
line1
line2
line3
etc...
然而,一旦完成循环,$newmsg
将显示为:
line1
line1
line2
line1
line2
line3
etc...
我在循环内将lappend
更改为append
,在循环内将其附加到$newmsg
后将set $seg
更改为""
,全部为no有用。想法?
我想,您正在寻找这样的东西:
set data "hello\nworld\nits\nme\nalex"
set linecounter 0
set newmsg ""
foreach line [split $data \n] {
incr linecounter
set seg "OBX|$linecounter|[string trimright $line]||||||V\n"
append newmsg $seg
}
puts "This is the new message: $newmsg"
这将创建其中包含 \n 换行符的字符串。 此代码的示例输出:
This is the new message: OBX|1|hello||||||V
OBX|2|world||||||V
OBX|3|its||||||V
OBX|4|me||||||V
OBX|5|alex||||||V
你得到奇怪的输出有两个原因: 1. append 需要变量名作为第一个参数。所以OBX|是它的名字,它的内容是在循环过程中增长的。 2. 回显列表用于用 {}
包装其项目