我的TCL脚本:
set a [open fruits.txt r]
set b [read $a]
foreach c $b {
puts "Fruits : $c"
set website [open website_name1.txt r]
set each_one [read $website]
foreach each $each_one {
puts "website name : $c"
}
}
fruits.txt
内容:
apple orange mango litchi banana
website_name1.txt
内容:
google.com yahoo.com metlife.com cisco.com span.com
现在,如果我运行上面的脚本,我将得到如下所示的输出:
D:\Desktop>tclsh statck_qns.tcl
Fruits : apple
website name : apple
website name : apple
website name : apple
website name : apple
website name : apple
Fruits : orange
website name : orange
website name : orange
website name : orange
website name : orange
website name : orange
Fruits : mango
website name : mango
website name : mango
website name : mango
website name : mango
website name : mango
Fruits : litchi
website name : litchi
website name : litchi
website name : litchi
website name : litchi
website name : litchi
Fruits : banana
website name : banana
website name : banana
website name : banana
website name : banana
website name : banana
D:\Desktop>
但我试图获得如下所示的输出:
Fruits : apple
website name : google.com
Fruits : orange
website name : yahoo.com
Fruits : mango
website name : metlife.com
Fruits : litchi
website name : cisco.com
Fruits : banana
website name : span.com
答案 0 :(得分:4)
您的代码存在许多问题。您在第二个循环中使用$c
,而它应该是$each
。此外,如果您只想将网站名称设置一次,则需要获得一个循环,同时循环遍历两个列表。
set a [open fruits.txt r]
set b [read $a]
set website [open website_name1.txt r]
set each_one [read $website]
foreach c $b each $each_one {
puts "Fruits : $c"
puts "website name : $each"
}
close $a
close $website
您可以使用上述格式的foreach
循环显示两个(或更多)列表,即:
foreach var1 list1 var2 list2 ... varn listn {
# code here
}
如果列表中的元素数量不同,那么您将开始在列表的变量名称中获取空字符串,并且元素数量较少。
答案 1 :(得分:1)
也可以使用while循环逐行阅读
set f_fruit [open fruits.txt r]
set f_web [open website_name1.txt r]
while {[gets $f_fruit fruit] != -1 && [gets $f_web website] != -1} {
puts "Fruits: $fruit"
puts "website name: $website"
}
close $f_fruit
close $f_web