TCL -- How to store and print table of values?

Viewed 8773

I know that you can "hack" nesting associative arrays in tcl, and I also know that with dictionaries (which I have no experience with) you can nest them pretty easily. I'm trying to find a way to store the values of a function that has two variables, and then at the end I just want to print out a table of the two variables (column and row headers) with the function values in the cells. I can make this work, but it is neither succinct nor efficient.

Here's what should be printed. The rows are values of b and columns are values of a (1,2,3,4,5 for simplicity):

                          b
          1       2       3       4       5
    1  y(1,1)  y(1,2)  y(1,3)  y(1,4)  y(1,5)
    2  y(2,1)  y(2,2)  y(2,3)  y(2,4)  y(2,5)
  a 3  y(3,1)  y(3,2)  y(3,3)  y(3,4)  y(3,5)
    4  y(4,1)  y(4,2)  y(4,3)  y(4,4)  y(4,5)
    5  y(5,1)  y(5,2)  y(5,3)  y(5,4)  y(5,5)

To store this, I imagine I would simply do two nested for loops over a and b and somehow store the results in nested dictionaries. Like have one dictionary with 5 entries, 1 for each value of b, and each entry in this is another dictionary for each value of b.

To print it, the only way I can think of is to just explicitly print out each table line and call each dictionary entry. I'm not too versed in output formatting with tcl, but I can probably manage there.

Can anyone think of a more elegant way to do this?

4 Answers
package require csv
package require struct::matrix

array set OPTS [subst {
    csv_input_filename            {input.csv}
}]

::struct::matrix indata
set chan [open $OPTS(csv_input_filename)]
csv::read2matrix $chan indata , auto
close $chan

# prints matrix as list format
puts [join [indata get rect 0 0 end end] \n]; 

# prints matrix as csv format
csv::joinmatrix indata

# cleanup
indata destroy

This is a one-liner way to print out a matrix as list or csv format respectively.

Related