1

1)

% expr "1==1"
1

2)

% expr "i==i"
invalid bareword "i"
in expression "i==i";
should be "$i" or "{i}" or "i(...)" or ...

Why am getting this error in step - 2

1) % if {"i" == "i"} {
    puts "hai"
  }
  hai



2) % if {i == "i"} {
   puts "hai"
  }

invalid bareword "i"
in expression "i == "i"";
should be "$i" or "{i}" or "i(...)" or ...

if {"i" == "i"} This is wotking with if condition .

Here I found like expr command evaluating only integers , not comparing strings , But the In "if" condition everything (integer as well as string) are evaluating .

How Things are working here ?

4

2 回答 2

9

答案在expr手册页中。

Operands may be specified in any of the following ways:
...
[4]    As a string enclosed in double-quotes.   The  expression  parser
       will  perform  backslash, variable, and command substitutions on
       the information between the quotes, and use the resulting  value
       as the operand

[5]    As a string enclosed in braces.  The characters between the open
       brace and matching close brace will be used as the operand with‐
       out any substitutions.
...

因此,expr可以比较字符串,但您必须将它们括在双引号或花括号中,具体取决于您是否要执行替换。

因此,在您的示例 2 中,您必须使用

% expr {"i" == "i"}

或者

% expr {{i} == {i}}

最好使用字符串比较操作数:

% expr {"i" eq "i"}
% expr {{i} eq {i}}

确保字符串的内容不会转换为数值。

于 2013-09-16T11:02:39.703 回答
0

在 Tcl 8.4 中

您可以使用

  %expr {"i" == "i"}

或者

  %expr ( "i" == "i" )

两种语法都可以。

于 2013-10-03T08:01:47.187 回答