为什么EXPR“我==我”失败,出现“无效的裸词”?(Why does expr “i==i” fa

2019-09-30 06:30发布

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”}这与如果条件wotking。

在这里,我发现像expr的命令仅评估整数,而不是比较字符串,但条件都(整数和字符串)正在评估在“如果”。

事情是如何工作的吗?

Answer 1:

答案是在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可以比较字符串,但是,你必须将它们用双引号或大括号取决于你是否想substituions执行与否。

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

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

要么

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

更好的用户字符串比较操作数:

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

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



Answer 2:

在Tcl的8.4

您可以使用

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

要么

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

这两种语法都可以工作。



文章来源: Why does expr “i==i” fail with “invalid bareword”?
标签: tcl