为什么 expr “i==i"因“无效的裸字"而失败? [英] Why does expr "i==i" fail with "invalid bareword"?

查看:30
本文介绍了为什么 expr “i==i"因“无效的裸字"而失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1)

% expr "1==1"1

2)

% expr "i==i"无效的裸字我"在表达式i==i"中;应该是 "$i" 或 "{i}" 或 "i(...)" 或 ...

为什么在第 2 步中出现此错误

1) % if {"i" == "i"} {放海"}海2) % if {i == "i"} {放海"}无效的裸字我"在表达式 "i == "i"" 中;应该是 "$i" 或 "{i}" 或 "i(...)" 或 ...

<块引用><块引用><块引用>

if {"i" == "i"} 这就是 if 条件.

在这里我发现像 expr 命令只计算整数,而不是比较字符串,但是在if"条件下,所有内容(整数和字符串)都在计算.

这里的工作如何?

解决方案

答案在 expr 手册页中.

操作数可以通过以下任何一种方式指定:...[4] 作为用双引号括起来的字符串.表达式解析器将执行反斜杠、变量和命令替换引号之间的信息,并使用结果值作为操作数[5] 作为用大括号括起来的字符串.开放之间的字符大括号和匹配的右大括号将用作操作数 -出任何替代品....

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

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

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

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

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

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

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

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 ?

解决方案

The answer is in the expr man page.

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

So, expr can compare strings, but you must enclose them in double quotes or curly braces, depending on whether you want substituions performed or not.

Therefore, in your example 2, you must use

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

or

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

Better to user the string comparison operands:

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

to be sure that the content of the string is not converted to numerical values.

这篇关于为什么 expr “i==i"因“无效的裸字"而失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆