为什么expr“i == i”因“无效的裸字”而失败?

时间:2013-09-16 10:27:44

标签: tcl

1)

% expr "1==1"
1

2)

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

为什么在步骤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 ...
  
    
      

如果{“i”==“i”}这是if条件的wotking。

    
  

在这里,我发现expr命令只评估整数,而不是比较字符串,但In“if”条件的所有内容(整数和字符串)都在评估。

事情在这里如何运作?

2 个答案:

答案 0 :(得分: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}}

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

答案 1 :(得分:0)

在Tcl 8.4中

你可以使用

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

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

这两种语法都可以。

相关问题