TCL使用变量作为键名获取数组值

时间:2015-06-19 14:46:04

标签: tcl

我有以下数组列表,其中包含IANA密码套件ID(密钥名称)及其对应的名称(值)

array set IANA_Ciphers [list {0000} {"TLS_NULL_WITH_NULL_NULL"} \
        {0001} {"TLS_RSA_WITH_NULL_MD5"} \
        {0002} {"TLS_RSA_WITH_NULL_SHA"} \
        {0003} {"TLS_RSA_EXPORT_WITH_RC4_40_MD5"} \
        [...]
        {C0AF} {"TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8"} ]

现在我需要能够动态访问此数组的值但是当我使用以下代码时,我得到错误“无法读取”IANA_Ciphers(0000)“:数组中没有这样的元素

set ciphers "000000010002"
set tmp [string range $ciphers 0 3] ;# which gives "0000"
puts $IANA_Ciphers($tmp) ;# throws the error

我做错了什么?

谢谢和问候

1 个答案:

答案 0 :(得分:0)

您应该将变量设置为

set ciphers "000000010002"

更新2

我不知道array set命令中的附加大括号是否是拼写错误。

array set IANA_Ciphers [list {0000} {"TLS_NULL_WITH_NULL_NULL"} \
        {0001} {"TLS_RSA_WITH_NULL_MD5"} \
        {0002} {"TLS_RSA_WITH_NULL_SHA"} \
        {0003} {"TLS_RSA_EXPORT_WITH_RC4_40_MD5"} \
        [...]
        {C0AF} {"TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8"} ]
} # This '}' is not needed at all.

你应该收到错误

--------
invalid command name "}"
    while executing
"}"

顺便说一句,没有它,我已经尝试过你的代码,它对我来说很好。

array set IANA_Ciphers [list {0000} {"TLS_NULL_WITH_NULL_NULL"} \
        {0001} {"TLS_RSA_WITH_NULL_MD5"} \
        {0002} {"TLS_RSA_WITH_NULL_SHA"} \
        {0003} {"TLS_RSA_EXPORT_WITH_RC4_40_MD5"} \
        {C0AF} {"TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8"} ]

set ciphers "000000010002"
set tmp [string range $ciphers 0 3] ;# which gives "0000"
puts "Key : $tmp"
puts "Value : $IANA_Ciphers($tmp)" 

输出

Key : 0000
Value : "TLS_NULL_WITH_NULL_NULL"