use*_*991 1 dictionary tcl catch-block
我想要一个proc,如果它的'参数是一个Tcl 8.5及以上的字典,它会做什么.我从Tcl dict命令中找不到任何直截了当的东西.我可以使用的代码是:
proc dict? {dicty} {
expr { [catch { dict info $dicty } ] ? 0 : 1 }
}
Run Code Online (Sandbox Code Playgroud)
是否有什么不使用catch,内置的东西?
谢谢.
您可以通过查看值是否为列表以及是否具有偶数个元素来测试值是否为字典; 所有偶数长度列表都可以用作词典(尽管很多都是自然不是规范的词典,因为重复键之类的东西).
proc is-dict {value} {
return [expr {[string is list $value] && ([llength $value]&1) == 0}]
}
Run Code Online (Sandbox Code Playgroud)
您可以查看Tcl 8.6中的实际类型,tcl::unsupported::representation
但不建议这样做,因为像文字这样的东西会在运行时转换为字典.以下是合法的,显示了您可以做的事情,并显示了限制(
% set value {b c d e}
b c d e
% tcl::unsupported::representation $value
value is a pure string with a refcount of 4, object pointer at 0x1010072e0, string representation "b c d e"
% dict size $value
2
% tcl::unsupported::representation $value
value is a dict with a refcount of 4, object pointer at 0x1010072e0, internal representation 0x10180fd10:0x0, string representation "b c d e"
% dict set value f g;tcl::unsupported::representation $value
value is a dict with a refcount of 2, object pointer at 0x1008f00c0, internal representation 0x10101eb10:0x0, no string representation
% string length $value
11
% tcl::unsupported::representation $value
value is a string with a refcount of 2, object pointer at 0x1008f00c0, internal representation 0x100901890:0x0, string representation "b c d e f g"
% dict size $value;tcl::unsupported::representation $value
value is a dict with a refcount of 2, object pointer at 0x1008f00c0, internal representation 0x1008c7510:0x0, string representation "b c d e f g"
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,Tcl中的类型有点滑(按设计),因此强烈建议您完全不依赖它们.