Tcl 做了一个",;“安全”;dict get命令的包装器,但可以';我做不到

Tcl 做了一个",;“安全”;dict get命令的包装器,但可以';我做不到,tcl,Tcl,当使用dict-get命令时,我已经厌倦了使用dict-exists来防止运行时错误,所以我将dict-get包装在一个“安全”版本中。但是,我不明白为什么它不起作用。dict exists命令似乎不接受我参数化键的方式。我没想到做这么简单的事情会遇到任何问题,但我一定是犯了一个愚蠢的错误。代码如下: #=================================================================================================

当使用
dict-get
命令时,我已经厌倦了使用
dict-exists
来防止运行时错误,所以我将
dict-get
包装在一个“安全”版本中。但是,我不明白为什么它不起作用。dict exists命令似乎不接受我参数化键的方式。我没想到做这么简单的事情会遇到任何问题,但我一定是犯了一个愚蠢的错误。代码如下:

#====================================================================================================
# dictGet
#
#   Desc:   Safe version of "dict get".  Checks to make sure a dict key exists before attempting to
#           retrieve it, avoiding run-time error if it does not.
#   Param:  dictName    -   The name of the dict to retrieve from.
#           keys        -   List of one or more dict keys terminating with the desired key from
#                           which the value is desired.
#   Return: The value of the dict key; -1 if the key does not exist.
#====================================================================================================
proc dictGet {theDict keys} {
    if {[dict exists $theDict [split $keys]]} {
        return [dict get $theDict [split $keys]]
    } else {
        return -1
    }
}

#====================================================================================================
#Test...
dict set myDict 0 firstName "Shao"
dict set myDict 0 lastName "Kahn"

puts [dictGet $myDict {0 firstName}]

split
命令不会更改键所在位置的字数。如果拆分列表
{0 firstName}
,则仍然会得到列表
{0 firstName}
。要获取单个键,请使用
{*}
展开列表

set theDict {0 {firstName foo} 1 {firstName bar}}
# -> 0 {firstName foo} 1 {firstName bar}
set keys {0 firstName}
# -> 0 firstName
list dict exists $theDict [split $keys]
# -> dict exists {0 {firstName foo} 1 {firstName bar}} {0 firstName}
list dict exists $theDict {*}$keys
# -> dict exists {0 {firstName foo} 1 {firstName bar}} 0 firstName
此外,如果您使用此选项:

proc dictGet {theDict args} {
您可以如下方式调用该命令:

dictGet $myDict 0 firstName
您仍然需要扩展
$args
,但至少在我看来,使用类似于标准
dict get
调用的调用似乎是个好主意


文档:,,,

使用
{*}$keys
而不是
[split$keys]
。谢谢。当我在线编译它时,它起作用了,但由于某种原因在Eclipse中不起作用。通过谷歌搜索,我发现这个叫做“扩展”操作符。关于为什么解释器在我展开列表之前无法识别列表中的各个项目,有什么见解吗?回答得很好,我喜欢使用args使调用更自然。