-1

If I put only below it works.

"\{[lindex ($columns) 1] - 30.3]"

If I put as below, it doesnt work. Wonder why?

"\{[lindex ($columns) 1] - 30.3] [expr [lindex ($columns) 2] -30.3] \}"

My script as below:

foreach line $lines {
    set columns [split $line " "]
    puts "\{[lindex ($columns) 1] - 30.3] [expr [lindex ($columns) 2] -30.3] \}"
}
Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
Kimi
  • 43
  • 1
  • 7
  • The first version is… only really working by chance. It has non-matching square brackets, but in the way that isn't a syntax error. – Donal Fellows Apr 23 '21 at 08:00

1 Answers1

1

The problem is that you're writing ($columns) instead of $columns, which is concatenating parentheses on the list you're passing to lindex. In this case, I suspect that the list has three simple elements (e.g., 1 2 3) and the result of the concatenation is (1 2 3). The middle element at index 1 is still fine, but the element at the end (index 2) is now 3) and that's non-numeric.

The whole thing is a syntax error. Here's how to write it correctly:

puts "\{[expr {[lindex $columns 1] - 30.3}] [expr {[lindex $columns 2] -30.3}] \}"

However, in this case it might instead be a bit clearer to write this:

lassign [split $line " "] c1 c2 c3
puts [format "{%f %f}" [expr {$c2 - 30.3}] [expr {$c3 - 30.3}]]
Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
  • %.4f - seems to round up the final number. What would be the syntax, if I do not want the final number to be round up to 3 digit (ie: 12.1230) – Kimi Apr 23 '21 at 11:07
  • You could use `%s` to get no rounding at all (assuming recent-enough Tcl). Otherwise there's lots of options for formatting a number. Worth asking that as a separate question where you lay out exactly what you want to get out of it… – Donal Fellows Apr 23 '21 at 14:16