How to print in tabular format in tcl?

I am trying to print data in tabular format in tcl. Suppose I have three arrays: -

GOLD, TEST, DIFF , and it has some values. I want to print in the following format: -

GOLD TEST DIFF
----------- -------- --- ------
1 hi hi
2 Stack Format
3 guys for
4 TCL print

Could you suggest something?

+6
source share
4 answers

Here's the code that does what you want with a single foreach loop. There is no need to create temporary lists - if you have common indexes for arrays (you did not specify).

 array set GOLD {a 1 b 2 c 3 d 4} array set TEST {d TCL c Guys b Stack a Hello} array set DIFF {a Hi c for b Format d print} foreach idx [lsort [array names GOLD]] { puts "$GOLD($idx)\t$TEST($idx)\t$DIFF($idx)" } 

If you do not have common indexes for arrays (then I wonder about the utility of the printed table), you can do this (although the relative ordering is undefined):

 foreach {gidx gval} [array get GOLD] {tidx tval} [array get TEST] {didx dval} [array get DIFF] { puts "$gval\t$tval\t$dval" } 
+3
source

I would use the format command in conjunction with foreach to accomplish what you ask for. I assume that you actually have 3 lists, not 3 arrays, as the gold, test, diff values ​​will seem to be related to each other in some way.

 set goldList {1 2 3 4} set testList {Hello Stack Guys TCL} set diffList {Hi Format for print} set formatStr {%15s%15s%15s} puts [format $formatStr "GOLD" "TEST" "DIFF"] puts [format $formatStr "----" "----" "----"] foreach goldValue $goldList testValue $testList diffValue $diffList { puts [format $formatStr $goldValue $testValue $diffValue] } # output GOLD TEST DIFF ---- ---- ---- 1 Hello Hi 2 Stack Format 3 Guys for 4 TCL print 
+11
source

First convert arrays to lists:

 set GOLDList "" set keyList [array names GOLD] foreach key $keyList { lappend GOLDList $GOLD($key) } 

Then you can use the foreach snippet:

 set GOLDList "1 2 3 4"; #1st list set TESTList "Hello Stack Guys TCL"; #2nd list set DIFFList "Hi Format for print"; #3rd list foreach c1 $GOLDList c2 $TESTList c3 $DIFFList { puts $c1\t$c2\t$c3 } 

This is the result (you need to print an additional header)

 1 Hello Hi 2 Stack Format 3 Guys for 4 TCL print 
+4
source

Another tricky option is to use the report package from tcllib.

But this is probably not worth it for a simple case.

+2
source

Source: https://habr.com/ru/post/892657/


All Articles