首页 > 解决方案 > Tcl 中的数值比较

问题描述

我想知道如何在 TCL 中获取数值。我的意思是,如果该值不是数字,则结果应该失败,否则通过。

以下是我尝试过的;

set trueKIND false
set trueKINDlist [list 1 2 3 4 5 6 7 8 9 10]

if {[lsearch -exact $trueKINDlist $Registrant(KIND)] >= 0} {
    set trueKIND true
}

但是如果 trueKINDlist > 10 的值会发生什么,这段代码肯定会失败......

有人可以告诉我如何在 TCL 中写这个吗?或协助我与操作员一起使用以实现此目的...

谢谢玛蒂

标签: tcl

解决方案


你必须考虑你想要什么样的验证。例如,如果您只想验证该值是否为整数,任何整数,请执行以下操作:

if {![string is entier -strict $value]} {
    error "$value is not an integer"
}

(还有string is integer, 但由于历史原因,它使用受限制的 32 位范围,并string is wide使用 64 位范围。对于浮点数,请使用string is double. The-strict此处是必需的;没有它,也接受空字符串;同样,这是出于历史原因。)

当您希望值处于特定范围时,您可以使用复合条件:

if {![string is entier -strict $value] || !($value >= 0 && $value <= 10)} {
    error "$value is not an integer in the range (0..10)"
}

如果您经常这样做,请使用一个过程使其更清晰:

proc IntegerInRange {value lowerBound upperBound} {
    expr {[string is entier -strict $value] && $value >= $lowerBound && $value <= $upperBound}
}

if {![IntegerInRange $value 0 10]} {
    error "$value is not an integer in the range (0..10)"
}
if {![IntegerInRange $value2 3 25]} {
    error "$value2 is not an integer in the range (3..25)"
}

推荐阅读