使用三元运算符的TCL条件命令

使用三元运算符的TCL条件命令,tcl,ternary-operator,Tcl,Ternary Operator,是否可以使用TCL的三元运算符运行条件命令 使用if语句 if {[string index $cVals $index]} { incr As } { incr Bs } 我想使用三元运算符,如下所示,但我得到一个错误 执行“[string index$cVals$index]时命令名“1”无效 ?增量As:增量Bs“ 对于三元条件,我们应该只使用布尔值,0或1 因此,不能直接使用字符串索引,因为它将返回字符或空字符串。您必须比较字符串是否为

是否可以使用TCL的三元运算符运行条件命令

使用if语句

   if {[string index $cVals $index]} {
       incr As
    } {
       incr Bs
    }
我想使用三元运算符,如下所示,但我得到一个错误

执行“[string index$cVals$index]时命令名“1”无效 ?增量As:增量Bs“


对于三元条件,我们应该只使用布尔值,0或1

因此,不能直接使用
字符串索引
,因为它将返回字符或空字符串。您必须比较字符串是否为空

此外,对于条件的通过/失败标准,我们必须给出文字值。应该使用来计算表达式的值

一个基本的例子是

% expr { 0 < 1 ? "PASS" : "FAIL" }
PASS
% expr { 0 > 1 ? "PASS" : "FAIL" }
FAIL
%
现在,你能对你的问题做些什么

如果您想使用任何命令(如您的案例中的
incr
),则应在方括号内使用该命令,以将其标记为命令

% set cVals "Stackoverflow"
Stackoverflow
% set index 5
5
% # Index char found. So, the string is not empty.
% # Thus, the variable 'As' is created and updated with value 1
% # That is why we are getting '1' as a result. 
% # Try running multiple times, you will get the updated values of 'As'
% expr {[string index $cVals $index] ne {} ? [incr As] : [incr Bs] }
1
% info exists As
1
% set As
1
% # Note that 'Bs' is not created yet...
% info exists Bs
0
%
% # Changing the index now... 
% set index 100
100
% # Since the index is not available, we will get empty string. 
% # So, our condition fails, thus, it will be increment 'Bs'
% expr {[string index $cVals $index] ne {} ? [incr As] : [incr Bs] }
1
% info exists Bs
1
%

谢谢,太好了!,我想知道,无论我们使用三元运算符还是if语句,性能是否仍然相同?if语句在幕后使用expr,所以我猜大概是一样的。是的。应该是。(可能是多纳尔·费罗斯先生/格伦·杰克曼先生会评论我在内部幕后工作方面是否错了。)无论怎样,表现都不应该是一个问题。我会使用
if
,因为它更具可读性和可维护性(不太“聪明”)。性能应该差不多——字节码中的性能都是一样的——但与其猜测,不如用
时间来衡量它,并确知。
% expr { 0 > 1 ? 100 : -200 }
-200
% expr { 0 < 1 ? 100 : -200 }
100
%
% set cVals "Stackoverflow"
Stackoverflow
% set index 5
5
% # Index char found. So, the string is not empty.
% # Thus, the variable 'As' is created and updated with value 1
% # That is why we are getting '1' as a result. 
% # Try running multiple times, you will get the updated values of 'As'
% expr {[string index $cVals $index] ne {} ? [incr As] : [incr Bs] }
1
% info exists As
1
% set As
1
% # Note that 'Bs' is not created yet...
% info exists Bs
0
%
% # Changing the index now... 
% set index 100
100
% # Since the index is not available, we will get empty string. 
% # So, our condition fails, thus, it will be increment 'Bs'
% expr {[string index $cVals $index] ne {} ? [incr As] : [incr Bs] }
1
% info exists Bs
1
%