【问题标题】:square brackets in tcl arraystcl 数组中的方括号
【发布时间】:2013-12-19 13:06:45
【问题描述】:

我有以下问题:

set start "input[0]"
set end   "output[0]"
set myArray($start,$end,pin) 1
set x "input[0]"
set y "output[0]"
set test [array names myArray $x,$y,pin]
puts "\n$test"

输出应该是:

input[0],output[0]

但输出是:

{}

如果我这样做:

set test [array names myArray *,*,pin]
puts "\n$test"

输出是:

input[0],output[0]

另外,如果我将 [] 替换为 {} ie.input{0},output{0} 原始代码有效。

谁能告诉我这里发生了什么?如何转义 [] 括号?

【问题讨论】:

    标签: arrays tcl square-bracket


    【解决方案1】:

    好吧,让我们看看这里发生了什么:

    set start "input[0]"
    

    这将执行命令0。我不知道那是做什么的,但你可能不想要那样。使用\ 转义括号或使用{} 将名称括起来。

    同样适用于

    set end   "output[0]"
    # ...
    set x "input[0]"
    set y "output[0]"
    

    但看起来你没有这个问题。

    接下来就是将 glob 模式传递给array names

    set test [array names myArray $x,$y,pin]
    

    Tcl 在全局模式中使用[] 进行字符选择,类似于正则表达式。所以你的模式只会匹配input0,output0,pin。您可以通过将-exact 开关传递给array names 来避免这种情况:

    set test [array names myArray -exact $x,$y,pin]
    

    或者你可以用反斜杠再次转义括号(注意模式应该看起来像input\[0\],input\[1\],pinTcl做了各种替换之后。)

    【讨论】:

    • 这适用于上述情况。我还有另一种无法使用 -exact 的情况:set test [array names myArray $x,$y,*,length] -exact 选项在这里失败,原因很明显。我无法使用-regexp 解决$x 和$y 和* 中的方括号。知道这里发生了什么吗?
    • @user3119236 你为什么要使用array names?在我看来,你做错了事,你需要退后一步,想想你想要做什么。也许将字典放在数组元素中会更合适,或者将事物映射为某种对象?
    • 我们的字符串映射在所有出现的方括号前加上斜线: set checkname [string map {[ \\[ ] \\]} "$x,$y,*,length"] set test [数组名称 myArray $checkname]
    猜你喜欢
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    相关资源
    最近更新 更多