标签:
expr is for Tcl to do math type operations. It takes all of its arguments ("2 + 2" for example) and evaluates the result as a Tcl "expression", and returns the value. Many commands use expr
behind the scenes in order to evaluate test expressions, such as if
, while
and for
loops.
tip: enclosing the arguments to expr
in curly braces will result in faster code. So do expr {$i * 10}
instead of simply expr $i * 10
1) Operators
- + ~ !
Unary minus, unary plus, bit-wise NOT, logical NOT. None of these operators may be applied to string operands, and bit-wise NOT may be applied only to integers.
**
eq
) or inequality (ne
). and two operators for checking if a string is contained in a list (in
) or not (ni
). These operators all return 1 (true) or 0 (false). Using these operators ensures that the operands are regarded exclusively as strings (and lists), not as possible numbers.^
Bit-wise exclusive OR. Valid for integer operands only.
|
Bit-wise OR. Valid for integer operands only.
&&
Logical AND. Produces a 1 result if both operands are non-zero, 0 otherwise. Valid for numeric operands only (integers or floating-point).
||
Logical OR. Produces a 0 result if both operands are zero, 1 otherwise. Valid for numeric operands only (integers or floating-point).
x?y:z
If-then-else. If x evaluates to non-zero, then the result is the value of y. Otherwise the result is the value of z. The x operand must have a numeric value.
2) Example
1 set X 100 2 set Y 256 3 set Z [expr {$Y + $X}] 4 set Z_LABEL "$Y plus $X is " 5 6 puts "$Z_LABEL $Z" 7 puts "The square root of $Y is [expr { sqrt($Y) }]\n" 8 9 puts "Because of the precedence rules \"5 + -3 * 4\" is: [expr {-3 * 4 + 5}]" 10 puts "Because of the parentheses \"(5 + -3) * 4\" is: [expr {(5 + -3) * 4}]" 11 12 set A 3 13 set B 4 14 puts "The hypotenuse of a triangle: [expr {hypot($A,$B)}]" 15 16 # 17 # The trigonometric functions work with radians ... 18 # 19 set pi6 [expr {3.1415926/6.0}] 20 puts "The sine and cosine of pi/6: [expr {sin($pi6)}] [expr {cos($pi6)}]" 21 22 # 23 # Working with arrays 24 # 25 set a(1) 10 26 set a(2) 7 27 set a(3) 17 28 set b 2 29 puts "Sum: [expr {$a(1)+$a($b)}]"
标签:
原文地址:http://www.cnblogs.com/mengdie/p/4683618.html