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

i got  error:can't use non-numeric string as operand of "&"

I have try :

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

what i suppose to do?

eniac05
  • 477
  • 4
  • 10
  • 23
  • 1
    This code works for me (except for the third variant, which does give the error message you mention), but you might want to use `&&` (logical and) rather than `&` (bitwise and). – Peter Lewerin Jan 25 '14 at 12:52

1 Answers1

6

The expr command in Tcl allows two forms of AND operations: bitwise (using the operator &) and logical (using the operator &&). The bitwise operator only allows integer operands: the logical operator can deal with both boolean and numeric (integer and floating point values; 0 or 0.0 means false in this case) operands. Use the logical AND operator unless you specifically want to work with bit patterns.

An expression like

$foo eq "abc" && $bar eq "def"

works because the eq operators evaluate to boolean values (BTW: prefer the new eq (equal) operator to == if you're making string equality comparisons, as it's more efficient), leaving && with two boolean operands.

The following code, however

{$foo eq "abc"} && {$bar eq "def"}

fails because the braces prevent substitution and forces the && to deal with two string operands. In this case, the && operator gives the error message

expected boolean value but got "$foo eq "abc""

and the & operator gives the message

can't use non-numeric string as operand of "&"

which was what you got.

Peter Lewerin
  • 13,140
  • 1
  • 24
  • 27