How to write the different variable value in a file in TCL
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.
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 like
set fo [open test.txt w]
before your foreach
loop.
The second problem is that your code is going to write this content to the file:
data1
data2
data3
but probably you intend for it to write this content:
This is Data1 Value
This is Data2 Value
This is Data3 Value
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 the different_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 the set
command. After all, $
is just syntacic sugar for set
: $foo
is identical to [set foo]
. Therefore, I believe you need to rewrite the body of your loop as follows:
puts $fo [set $different_content]
So, putting it all together:
set data1 "This is Data1 Value\n"
set data2 "This is Data2 Value"
set data3 "\nThis is Data3 Value\n"
set fo [open test.txt w]
foreach different_content {data1 data2 data3} {
puts $fo [set $different_content]
}
close $fo
Eric's answer is great, but there's two other ways to write that foreach loop:
Method 1 (read the variables earlier):
foreach different_content [list $data1 $data2 $data3] {
puts $fo $different_content
}
Method 2 (use upvar 0
to make named aliases to variables):
foreach different_var {data1 data2 data3} {
upvar 0 $different_var different_content
puts $fo $different_content
}
You need to open the filehandle you are referring to as $fo
but have not actually opened:
set data1 "This is Data1 Value\n"
set data2 "This is Data2 Value"
set data3 "\nThis is Data3 Value\n"
set fo [open 'test.txt']
foreach different_content {data1 data2 data3} {
puts $fo $different_content
}
close $fo
精彩评论