TCL,如何命名包含另一个变量的变量 [英] TCL, How to name a variable that includes another variable

查看:60
本文介绍了TCL,如何命名包含另一个变量的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 TCL 中,我正在编写一个返回时钟深度的过程.但由于我有几个时钟,我想命名 var:depth_$clk

proc find_depth {} {foreach 时钟 $clocks {…设置 depth_$clk $max_depth回声 $depth_$clk}}

但我明白了:

<前>错误:无法读取depth_":没有这样的变量使用 error_info 获取更多信息.(CMD-013)

解决方案

你的问题是这一行:

 echo $depth_$clk

问题是 $ 的语法在之后只解析有限的一组字符作为变量名的一部分;$ 不是其中的一部分.相反,您可以使用带有 one 参数的 set 命令;$ 是有效的语法糖,但该命令允许您使用复杂的替换.

 echo [设置深度_$clk]

无论如何!

这里真正正确的做法是切换到使用关联数组.这是对您的代码的较大更改,但可以让您做更多事情,因为您可以正确访问数组元素名称中的替换:

proc find_depth {} {foreach 时钟 $clocks {…设置深度($clk)$max_depth回声 $depth($clk)}}

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)

解决方案

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)
    }
}

这篇关于TCL,如何命名包含另一个变量的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆