使用三元运算符的 TCL 条件命令
TCL conditional commands using ternary operator
是否可以使用 TCL 的三元运算符 运行 条件命令?
使用 if 语句
if {[string index $cVals $index]} {
incr As
} {
incr Bs
}
我想按如下方式使用三元运算符,但出现错误
invalid command name "1" while executing "[string index $cVals $index]
? incr As : incr Bs"
[string index $cVals $index] ? incr As : incr Bs
对于三元条件,我们应该只使用布尔值,0 或 1。
因此,您不能直接使用 string index
,因为它会 return 一个字符或空字符串。您必须比较字符串是否为空。
此外,对于 pass/fail 条件条件,我们必须给出字面值。您应该使用 expr 来评估表达式。
一个基本的例子可以是,
% expr { 0 < 1 ? "PASS" : "FAIL" }
PASS
% expr { 0 > 1 ? "PASS" : "FAIL" }
FAIL
%
请注意,我对字符串使用了双引号,因为它包含字母。如果是数字,则不必是双引号。 Tcl
将适当地解释数字。
% expr { 0 > 1 ? 100 : -200 }
-200
% expr { 0 < 1 ? 100 : -200 }
100
%
现在,如何解决您的问题?
如果您想使用任何命令(例如您的情况下的 incr
),它应该在方括号内使用,以将其标记为命令。
% set cVals "Whosebug"
Whosebug
% 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
%
是否可以使用 TCL 的三元运算符 运行 条件命令?
使用 if 语句
if {[string index $cVals $index]} {
incr As
} {
incr Bs
}
我想按如下方式使用三元运算符,但出现错误
invalid command name "1" while executing "[string index $cVals $index] ? incr As : incr Bs"
[string index $cVals $index] ? incr As : incr Bs
对于三元条件,我们应该只使用布尔值,0 或 1。
因此,您不能直接使用 string index
,因为它会 return 一个字符或空字符串。您必须比较字符串是否为空。
此外,对于 pass/fail 条件条件,我们必须给出字面值。您应该使用 expr 来评估表达式。
一个基本的例子可以是,
% expr { 0 < 1 ? "PASS" : "FAIL" }
PASS
% expr { 0 > 1 ? "PASS" : "FAIL" }
FAIL
%
请注意,我对字符串使用了双引号,因为它包含字母。如果是数字,则不必是双引号。 Tcl
将适当地解释数字。
% expr { 0 > 1 ? 100 : -200 }
-200
% expr { 0 < 1 ? 100 : -200 }
100
%
现在,如何解决您的问题?
如果您想使用任何命令(例如您的情况下的 incr
),它应该在方括号内使用,以将其标记为命令。
% set cVals "Whosebug"
Whosebug
% 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
%