在TCL中,如何使一个变量使用另一个变量的值
我需要在另一个变量中使用一个变量的值。
这就是我尝试过的..
set cmd_ts "foo bar"
set confCmds {
command1
command2
$cmd_ts
}
puts "confCmds = $confCmds"
但
confCmds =
command1
command2
foo bar
我没有得到:
confCmds =
command1
command2
$cmd_ts
PS 我尝试了以下无济于事
- $cmd_ts
- "$cmd_ts"
- {$cmd_ts}
- \$cmd_ts
I need to use the value of a variable inside another variable.
This is what I tried..
set cmd_ts "foo bar"
set confCmds {
command1
command2
$cmd_ts
}
puts "confCmds = $confCmds"
But instead of getting
confCmds =
command1
command2
foo bar
I am getting:
confCmds =
command1
command2
$cmd_ts
P.S. I tried the following to no avail
- $cmd_ts
- "$cmd_ts"
- {$cmd_ts}
- \$cmd_ts
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您必须按原样定义列表,则还可以使用 subst 命令,该命令将执行大括号阻止的替换:
If you must have the list defined as you have it, you can also use the subst command, which will perform the substitution that the curly braces are preventing:
(几乎)只要使用花括号,什么都不会起作用。 最好的建议是使用 list 命令:
我说(几乎)是因为您可以使用 subst 在 confCmds 上进行变量替换,但这并不是您真正想要的,而且充满危险。 您想要的是一个单词列表,其中一个或多个可以由变量定义。 这正是上述解决方案为您提供的。
如果需要,您可以使用反斜杠将命令分散到多行上:
此解决方案假定您想要的是一个 tcl 列表。 这可能是也可能不是您想要的,这完全取决于您如何在下游处理这些数据。
在评论中,您写道,您真正想要的是一串以换行符分隔的项目,在这种情况下,您可以只使用双引号,例如:
这将为您提供一个由换行符分隔的多行字符串。 尝试将其视为命令列表时要小心(即:不要执行“foreach foo $confCmds”),因为它可能会失败,具体取决于 $cmd_ts 中的内容。
(almost) nothing will work as long as you use curly braces. The best suggestion is to use the list command:
I say (almost) because you can use subst to do variable substitution on confCmds, but that's not really what you want and that is fraught with peril. What you want is a list of words, one or more of which may be defined by a variable. That is precisely what the above solution gives you.
If you want, you can spread the commands on more than one line by using the backslash:
This solution assumes that what you want is a tcl list. This may or may not be what you want, it all depends on how you treat this data downstream.
In a comment you wrote that what you really want is a string of newline-separated items, in which case you can just use double quotes, for example:
That will give you a string with multiple lines separated by newlines. Be careful of trying to treat this as a list of commands (ie: don't do 'foreach foo $confCmds') because it can fail depending on what is in $cmd_ts.
布莱恩的回答很好,除了我的代表无法修复的拼写错误。 (第一个命令中的列表应以方括号结束)。
如果您想对命令执行任何有用的操作,您可能希望将它们作为列表,但如果您只想将它们用新行分隔,请在最后执行以下操作:
Bryan's answer is good, apart from a typo I can't fix with my rep. (the list in the first command should be ended with a square bracket).
If you want to do anything useful with the commands, you probably want them as a list, but if you just want them separated by a new line do this at the end: