tclexpr

Tcl lindex and expr: non-numeric failure


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] \}"
}

Solution

  • 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}]]