variables - TCL regsub 到变量?

标签 variables tcl regsub

我正在设置宏、Set 和 Say。在程序中定义。

proc Set {key value args} {
    set ::$key $value
            set "::key2" "$key"
}

proc Say {key} {
puts $key
}

proc Say2 {key} {
set key3 [regsub "\%" $key "\$"]
puts $key3
eval puts $key3
}

这允许我执行以下操作:

Set "test" "this should display this test text"
Say $key2 ;#should display the key "test" which is what we just set
Say $test ;#presents the value of the key test

输出

% Set "test" "this should display this test text"
test
% Say $key2 ;#should display the key "test" which is what we just set
test
% Say $test ;#presents the value of the key test
this should display this test text

现在假设我想将变量 $ 重新分配给 %

Set "mouse" "squeak" ;#set key mouse with value string of "squeak"
Say $mouse ;#displays the value as set above correctly
Say2 %mouse ;#start using our own characters to represent variables - switch the % for a $ and then output

但是当我使用 eval 时,

 can't read "mouse": no such variable

输出

% Set "mouse" "squeak" ;#set key mouse with value string of "squeak"
mouse
% Say $mouse ;#displays the value as set above correctly
squeak
% Say2 %mouse ;#start using our own characters to represent variables
$mouse
can't read "mouse": no such variable

我觉得这很奇怪,因为我们在上面设置了它,我们可以使用标准 $ 调用该值,并且我可以证明 Say2 中的 regsub 正在工作,因为它应该用 $ 替换 %。

%mouse 变为 $mouse,这是一个有效的变量。 评估没有此类变量的 $mouse 输出

我错过了什么吗?

谢谢

最佳答案

问题出在 proc 上:

proc Say2 {key} {
    set key3 [regsub {%} $key {$}]
    puts $key3
    eval puts $key3 ;# here
}

$mouse 不存在在此proc。它不是作为参数传递,也不是使用 set 创建的。然而它存在于全局命名空间中。在这种情况下,实现它的一种方法是使用 uplevel:

proc Say2 {key} {
    set key3 [regsub {%} $key {$}]
    puts $key3
    uplevel puts $key3
}

我经常使用的另一个选项是 upvar 将变量带入内部(尽管在本例中,我们不再需要 $):

proc Say2 {key} {
    set key3 [regsub {%} $key {}]
    puts $key3
    upvar $key3 var
    puts $var
}

PS:我还继续删除了一些反斜杠,因为在这种情况下并不真正需要它们。

关于variables - TCL regsub 到变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52651478/

相关文章:

regex - Lookbehind 和 Lookaround 概念在 TCL 正则表达式引擎中有用吗?

regex - 使用regsub捕获查询字符串左侧的值

java - 在 Java 中高效地循环访问具有多个变量类型的对象数组

node.js - Socket.io 客户端特定变量

C++ 变量 - 声明和定义。遗产

php - PDOException with message SQLSTATE[42000] : 1064. 在传递变量而不是字符串时发生

python - Mac上的python安装可以强制使用tcl/tk 8.6吗?

tcl命令重定向到一个变量,tcl版本是8.4