我想了解用于字符串比较的TCL命令expr:
我尝试了以下方法:
expr {t eq t}
=> 1
expr {tru eq tr}
=> 0
expr {tru eq truee}
=> invalid bareword "truee" ...
expr {a eq a}
=> invalid bareword "a" ...
Run Code Online (Sandbox Code Playgroud)
单词t,tr,tru背后的魔力是什么?Tcl是否特别处理这些字符串?我知道如果我使用expr和eq,我必须引用字符串,但是我有一些使用这种比较形式的遗留程序.我想了解它.谢谢.
In Tcl,eq并ne进行字符串比较,同时==进行数值比较.
% expr {1 == 1.0}
1
% expr {1 eq 1.0}
0
%
Run Code Online (Sandbox Code Playgroud)
无论何时使用eq和输入非数字,都应该使用双引号或变量引用.您不能使用文字裸字符串表示法.
例如
% expr {"a" eq "b"}; # Strings with double quotes
0
% set i a
a
% expr {$i eq "a"}; # String with variable reference
1
% expr {a eq b}; # Literally using the string as bareword
invalid bareword "a"
in expression "a eq b";
should be "$a" or "{a}" or "a(...)" or ...
%
Run Code Online (Sandbox Code Playgroud)
此规则中有一个例外,Tcl布尔值起作用.
在Tcl,一个适当的布尔值是一个正确的整数,如C,零表示false,非零表示true,或者下列之一:
yes, true, on --> Boolean 1
no, false, off --> Boolean 0
Run Code Online (Sandbox Code Playgroud)
当它们被部分使用时,Tcl倾向于与任何已知项目匹配,并且相应地进行评估.
如果您expr使用这些特殊单词进行评估,那么它将返回相同的单词.
% expr {true}
true
% expr {false}
false
% expr {t}; # Tcl automatically matches internally and map it to 'true'
t
% expr {fa} ; # Similary, mapped to 'false'
fa
% expr {o} ; # Will throw error as it is conflicting with 'on' & 'off'
invalid bareword "o"
in expression "o";
should be "$o" or "{o}" or "o(...)" or ...
% expr {on}
on
% expr {of}; # Matching 'off' boolean
of
% if true {puts ya}
ya
% if n {puts ya}; # Matching boolean 'no'
% if f {puts ya}; # Matching boolean 'false'
% if false {puts ya}
% if yes {puts ya}
ya
% if y {puts ya}; # Matching boolean 'y'
ya
Run Code Online (Sandbox Code Playgroud)
因此,如果您的输入使用布尔值进行映射,则它们仍然有效,但仅作为字符串处理.
现在,让我们回到你原来的问题.
% expr {t eq t}; # Tcl mapped the 'true' boolean and string-wise both are same. So, returned 1
1
% expr {tru eq tr}; # Both mapped 'true'. But, string-wise differs. So, returned 0
% expr {tru eq truee}; # 'tru' mapped to 'true' and 'truee' is unknown. So error
invalid bareword "truee"
% expr {a eq a}; # Both are used literally, so error throw.
invalid bareword "a"
Run Code Online (Sandbox Code Playgroud)
现在,您的评论中的问题,
% expr {yes == true}; # String-wise, both are different. So, returned 0
0
Run Code Online (Sandbox Code Playgroud)