2016-08-24 72 views
3

我想了解字符串比較的TCL命令EXPR:什麼是與運營商均衡的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" ... 

背後是什麼法寶單詞t,tr,tru? Tcl是否特別處理這些字符串?我瞭解到,如果我用eq使用expr,則必須引用該字符串,但我有一些使用這種比較形式的傳統程序。我想了解它。謝謝。

回答

5

Tcl,eqne進行字符串比較,而==進行數字比較。

% expr {1 == 1.0} 
1 
% expr {1 eq 1.0} 
0 
% 

每當你使用的是eq,如果輸入非數字,那麼就應該用雙引號或具有可變參考使用。 您不能使用文字裸字符串表示法。

對於e.g

% 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 ... 
% 

有此規則,其中Tcl布爾進場一個例外。

Tcl,一個適當的布爾值可以是一個適當的整數,,像C,零含義假和非零含義真,或下列之一:

yes, true, on --> Boolean 1 
no, false, off --> Boolean 0 

當使用它們部分地,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 

所以,如果您的輸入是使用布爾值進行映射,它們仍然有效,但僅作爲字符串對待。

現在,讓我們回到你原來的問題。

% 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" 

現在,從評論你的問題,

% expr {yes == true}; # String-wise, both are different. So, returned 0 
0 
+0

我已經添加了從Tcl_GetBoolean所的文檔細節,擴大你的答案有點,因爲它似乎值得並未同時創造一個新的答案澄清這一級別。如果您不同意,請回滾編輯。 – Jackson

+0

@傑克遜:你測試過了嗎?縮寫不起作用併產生錯誤。 – slebetman

+0

感謝您的回答。現在我明白這個值是由tcl解釋爲布爾值的。但是,爲什麼'expr {yes == true}'返回'0'?我預計'1'。 – tjroamer