tcl 中的嵌套 foreach 循环

Nested foreach loops in tcl

我找遍了所有地方,但没有找到好的答案。我正在尝试在 tcl 中编写嵌套的 foreach 循环,从两个不同的文本文件中读取行。内部 foreach 循环将 运行 完全通过,但外部 foreach 循环将在仅评估文件中的第一行后中断。文本文件看起来像这样(除了大得多)。

input1.txt:

1
2
3
4
5
6
7
8
9
10

input2.txt:

a
b
c
d
e
f
g
h
i
j

我的嵌套 foreach 循环是这样构造的:

# Open file 1;
set FID1 [open input1.txt r];

# Open file 2
set FID2 [open input2.txt r];

# Open an output file to check the foreach loops;
set outFID [open outputcheck.txt w];

# Nest the foreach loops to read both files
foreach PropLine [split [read $FID1] \n] {
    foreach GMprop [split [read $FID2] \n] {
        puts $outFID "$PropLine $GMprop";
    }
}

close $FID1;
close $FID2;
close $outFID;

我的 outputcheck.txt 文件包含

1 a
1 b
1 c
1 d
1 e
1 f
1 g
1 h
1 i
1 j

我运行通过 OpenSEES.exe 可执行程序在装有 Windows 7 操作系统的 PC 上执行此代码。

提前感谢您的任何见解。

如果您想对文件 2 对文件 1 的每一行进行处理,那么

foreach PropLine [split [read $FID1] \n] {
    foreach GMprop [split [read $FID2] \n] {
        puts $outFID "$PropLine $GMprop";
    }
    # jump back to the start of the file, so you can re-read it
    # for the next iteration of the outer foreach loop
    seek $FID2 0 start
}

但是,看起来你只是想配对这些线,所以

foreach PropLine [split [read -nonewline $FID1] \n] \
        GMprop   [split [read -nonewline $FID2] \n] \
{
    puts $outFID "$PropLine $GMprop";
}

Tcl 允许您同时迭代多个列表,非常方便:http://tcl.tk/man/tcl8.6/TclCmd/foreach.htm

尽管我很想逐行阅读文件:

while {true} {
    set status1 [gets $FID1 PropLine]
    set status2 [gets $FID2 GMprop]
    if {$status1 == -1 && $status2 == -1} break
    puts $outFID "$PropLine $GMprop"
}