如何在tcl中使用eval语句

时间:2011-04-18 09:30:56

标签: tcl evaluation

所以基本上在我的tcl脚本中,我生成了一行必须执行的tcl代码(即我在运行时提出了这条指令)。一旦我有tcl指令说例如put“hello world $ test_var”。如何使用tcl执行此操作?

我是否使用eval命令或什么?

3 个答案:

答案 0 :(得分:4)

eval命令是一种合理的方法,但您可能需要考虑使用catch,因为这会捕获在评估生成的代码期间发现的任何问题,例如这样:

# Generate the code somehow
set variable {puts "hello word $test_var"}

# Execute and trap problems
if {[catch $variable resultMsg]} {
    # An error (or other exception) happened
    puts stderr "BOOM, Error! $resultMsg"
}

答案 1 :(得分:2)

在较新版本的Tcl中,您可以使用{*}语法,而不是使用效果非常好的[eval]。 例如:

set cmd "puts"
lappend cmd "abcd ef"
{*}$cmd

请注意,使用list命令构建命令是一个好习惯,这样您就不会遇到引用问题。

答案 2 :(得分:1)

我担心你没有其他合理的选择而不是使用eval命令,例如:

set variable {puts "hello world $test_var"}
eval $variable