TCL, How to name a variable that includes another variable

谁说胖子不能爱 提交于 2020-01-14 05:25:11

问题


In TCL, I'm writing a procedure that returns the depth of a clock. But since I have several clocks I want to name the var: depth_$clk

proc find_depth {} {    
    foreach clk $clocks {    
        …    
        set depth_$clk $max_depth    
        echo $depth_$clk    
    }    
}    

But I get:

Error: can't read "depth_": no such variable
        Use error_info for more info. (CMD-013)

回答1:


Your problem is this line:

    echo $depth_$clk    

The issue is that the syntax for $ only parses a limited set of characters afterwards for being part of the variable name; the $ is not part of that. Instead, you can use the set command with one argument; $ is effectively syntactic sugar for that, but the command lets you use complex substitutions.

    echo [set depth_$clk]

HOWEVER!

The real correct thing to do here is to switch to using an associative array. It's a bit larger change to your code, but lets you do more as you've got proper access to substitutions in array element names:

proc find_depth {} {
    foreach clk $clocks {
        …
        set depth($clk) $max_depth
        echo $depth($clk)
    }
}


来源:https://stackoverflow.com/questions/44605149/tcl-how-to-name-a-variable-that-includes-another-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!