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

eri*_*ons 4 tcl ternary-operator

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

使用 if 语句

   if {[string index $cVals $index]} {
       incr As
    } {
       incr Bs
    }
Run Code Online (Sandbox Code Playgroud)

我想按如下方式使用三元运算符,但出现错误

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

[string index $cVals $index] ? incr As : incr Bs
Run Code Online (Sandbox Code Playgroud)

Din*_*esh 6

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

所以,你不能string index直接使用,因为它会返回一个字符或空字符串。您必须比较字符串是否为空。

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

一个基本的例子可以是,

% expr { 0 < 1 ? "PASS" : "FAIL" }
PASS
% expr { 0 > 1 ? "PASS" : "FAIL" }
FAIL
%
Run Code Online (Sandbox Code Playgroud)

请注意,我对字符串使用了双引号,因为它包含字母。在数字的情况下,它不必是双引号。Tcl将适当地解释数字。

% expr { 0 > 1 ? 100 : -200 }
-200
% expr { 0 < 1 ? 100 : -200 }
100
%
Run Code Online (Sandbox Code Playgroud)

现在,可以对您的问题做些什么?

如果您想使用任何命令(例如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
%
Run Code Online (Sandbox Code Playgroud)

  • 无论哪种方式,性能都不应该成为问题。我会使用`if`,因为它更具可读性和可维护性(不那么“聪明”)。 (3认同)