如何在TCL中将不同的变量值写入文件中
如何使用 foreach 循环在 TCL 中写入不同的变量值。
情况是这样的:
set data1 "This is Data1 Value\n"
set data2 "This is Data2 Value"
set data3 "\nThis is Data3 Value\n"
foreach different_content {data1 data2 data3} {
puts $fo $different_content
}
close $fo
}
但是它不起作用。
How to write the different variable value in TCL using the foreach loop.
Here this is the situation:
set data1 "This is Data1 Value\n"
set data2 "This is Data2 Value"
set data3 "\nThis is Data3 Value\n"
foreach different_content {data1 data2 data3} {
puts $fo $different_content
}
close $fo
}
But it is not working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
代码片段存在多个问题。第一个也是最简单的错误是您没有在任何地方打开文件
fo
。除非在此处未显示的代码中的其他位置完成此操作,否则您需要在
foreach
循环之前添加类似的内容。第二个问题是您的代码要将以下内容写入文件:
但您可能打算让它写入以下内容:
这里的错误更加微妙。您的循环正在执行的操作是将
different_content 设置为每个感兴趣的变量的 名称,但您需要这些变量的值。本质上,您需要双重取消引用
different_content 变量。在变量名称的开头添加
$
可提供一级取消引用。不幸的是,对于 Tcl,你不能仅仅在前面加上另一个$
来获得第二级。但您可以使用set
命令。毕竟,$
只是set
的语法糖:$foo
与[set foo]
相同。因此,我相信您需要按如下方式重写循环体:因此,将它们放在一起:
There are multiple problems with the fragment of code. The first and simplest error is that you have not anywhere opened the file
fo
. Unless that is done elsewhere in code you haven't shown here, you need to add something likebefore your
foreach
loop.The second problem is that your code is going to write this content to the file:
but probably you intend for it to write this content:
Here the error is more subtle. What your loop is doing is setting
different_content
to the name of each variable of interest, but you want the value of those variables. Essentially you need to doubly dereference thedifferent_content
variable. Adding a$
at the start of the variable name gives you one level of dereferencing. Unfortunately with Tcl, you can't just slap another$
onto the front to get the second level. But you can use theset
command. After all,$
is just syntacic sugar forset
:$foo
is identical to[set foo]
. Therefore, I believe you need to rewrite the body of your loop as follows:So, putting it all together:
Eric 的回答很好,但是还有另外两种方法可以编写 foreach 循环:
方法 1(之前读取变量):
方法 2(使用
upvar 0
为变量创建命名别名):Eric's answer is great, but there's two other ways to write that foreach loop:
Method 1 (read the variables earlier):
Method 2 (use
upvar 0
to make named aliases to variables):您需要打开您引用为
$fo
但实际上尚未打开的文件句柄:You need to open the filehandle you are referring to as
$fo
but have not actually opened: