如何从字典中获取无效的 Tcl 值并针对整数进行测试?
How to have invalid Tcl value from a dict and test against an integer?
在我的 Tcl 中,我有一个可能不存在的字典查找,所以我想做这样的事情:
set result [dict exists $values "key"] ? [dict get $values "key"] : "<not present>"
但是,三元运算符正在评估未采用的子句并且失败。
稍后我想看看字典值是否为 10,我尝试了所有这些并且 none 结果是 "<not present>"
:
set test [expr $result == 10]
set test [expr [string is integer $result] && [expr $result == 10]]
set test [expr [string is integer $result] ? [expr $result == 10] : false]
Tcl 测试字典键是否存在且其值是否等于 10 的方法是什么?
我宁愿不使用数值(例如,-99
)而不是 "<not present>"
,这样我可以在使用 puts 结果时看到找不到该值。
您只是缺少实现三元运算符的 expr
命令:
set result [expr {[dict exists $values key] ? [dict get $values key] : "<not present>"}]
或者,只需使用更详细的 if
if {[dict exists $values key]} {
set result [dict get $values key]
} else {
set result "<not present>"
}
您缺少 expr 的大括号:请参阅 https://wiki.tcl-lang.org/page/Brace+your+expr-essions
set result "<not present>"
set test [expr $result == 10] ;# => missing operand at _@_
;# => in expression "_@_<not present> == 10"
set test [expr {$result == 10}] ;# => 0
在我的 Tcl 中,我有一个可能不存在的字典查找,所以我想做这样的事情:
set result [dict exists $values "key"] ? [dict get $values "key"] : "<not present>"
但是,三元运算符正在评估未采用的子句并且失败。
稍后我想看看字典值是否为 10,我尝试了所有这些并且 none 结果是 "<not present>"
:
set test [expr $result == 10]
set test [expr [string is integer $result] && [expr $result == 10]]
set test [expr [string is integer $result] ? [expr $result == 10] : false]
Tcl 测试字典键是否存在且其值是否等于 10 的方法是什么?
我宁愿不使用数值(例如,-99
)而不是 "<not present>"
,这样我可以在使用 puts 结果时看到找不到该值。
您只是缺少实现三元运算符的 expr
命令:
set result [expr {[dict exists $values key] ? [dict get $values key] : "<not present>"}]
或者,只需使用更详细的 if
if {[dict exists $values key]} {
set result [dict get $values key]
} else {
set result "<not present>"
}
您缺少 expr 的大括号:请参阅 https://wiki.tcl-lang.org/page/Brace+your+expr-essions
set result "<not present>"
set test [expr $result == 10] ;# => missing operand at _@_
;# => in expression "_@_<not present> == 10"
set test [expr {$result == 10}] ;# => 0