2

What is the function to get absolute value of a expr statement. For example expr [$a - $b ]. Now the solution can be -ve or +positive number. But I want the +ve value out.

I want to use it like if { |$diff_a| > 0 & |$diff_b| >0 } { ....

Im using tcl 8.4.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
user2095095
  • 31
  • 1
  • 3
  • 5
  • 1
    Have you even googled for this? Just googling for your question title comes up with the answer and many examples. – atk Mar 18 '13 at 02:20
  • abs (x) does not work in tcl 8.4. other solution are like if { $diff_a > 0 } { puts $diff_a } else { puts - $diff_a } – user2095095 Mar 18 '13 at 02:21
  • did you just typo? Or are you really trying abc()? – atk Mar 18 '13 at 02:22
  • @user2095095: are you sure about that? The 8.4 man page lists `abs` as a valid function. http://tcl.tk/man/tcl8.4/TclCmd/expr.htm#M21 – Bryan Oakley Mar 18 '13 at 02:24
  • @user2095095: what error do you get when you try to use abs()? – atk Mar 18 '13 at 02:26

2 Answers2

4

I would like to add, that the 'abs' command can only be used within a mathematical expression in Tcl, so the correct example would be:

if {[expr abs($diff_a)] > 0} {...}

For further information I refer to the expr man page as specified in the answer above.

  • 1
    This answer is subtly incorrect. While it's true it can only be used with a mathematical expression, you don't need to call `expr` inside an if statement. `if` already treats it's first argument as an expression, so `if {abs($diff_a) > 0}` is perfectly valid. – Bryan Oakley Jul 15 '14 at 18:23
3

You would use the abs function:

if {abs($diff_a) > 0 ...} ...

Note that abs only works in the context of an expression (eg: by calling expr), but also note that the first argument to if is evaluated as an expression.

abs is documented on the expr man page in versions prior to tcl 8.4. Starting with 8.5 it's on the mathfunc man page.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • thanks just realized it work. I was trying to set abs on the expr function and that was not working. How can I point a line next to current line in TCL after this if loop is true.(Im reading a file & doing some mathematical operation in it) – user2095095 Mar 18 '13 at 02:29
  • @user What does “set abs on the expr function” look like in code? – Donal Fellows Mar 18 '13 at 09:02