不能在TCL中使用非数字字符串作为"&"的操作数

eni*_*c05 2 tcl

if {   ($name1 == "john")   &   ($name2 == "smith")  } { puts "hello world" }

i got  error:can't use non-numeric string as operand of "&"
Run Code Online (Sandbox Code Playgroud)

我试过了:

if {   $name1 == "john"   &   $name2 == "smith"  } { puts "hello world" }
if {   {$name1 == "john"}   &   {$name2 == "smith"}  } { puts "hello world" }
Run Code Online (Sandbox Code Playgroud)

我想做什么?

Pet*_*rin 6

exprTcl中的命令允许两种形式的AND操作:按位(使用运算符&)和逻辑(使用运算符&&).按位运算符仅允许整数操作数:逻辑运算符可以处理布尔值和数值(整数和浮点值; 0或0.0在这种情况下表示为假)操作数.除非您特别想使用位模式,否则请使用逻辑AND运算符.

一个表达式

$foo eq "abc" && $bar eq "def"
Run Code Online (Sandbox Code Playgroud)

因为eq运算符求值为布尔值(BTW:如果你正在进行字符串相等比较,则更喜欢新的eq(相等)运算符==,因为它更有效),留下&&两个布尔操作数.

但是,以下代码

{$foo eq "abc"} && {$bar eq "def"}
Run Code Online (Sandbox Code Playgroud)

失败,因为大括号阻止替换并强制&&处理两个字符串操作数.在这种情况下,&&操作员会给出错误消息

expected boolean value but got "$foo eq "abc""
Run Code Online (Sandbox Code Playgroud)

并且&操作员给出消息

can't use non-numeric string as operand of "&"
Run Code Online (Sandbox Code Playgroud)

这就是你得到的.