Friday, January 29, 2010

Scrip reworked in to a proc..

Last night posted a simple script to format a list of strings into rows, which when inserted into a text widget would produce a table of column ordered entries. Well, here's the modified code wrapped up into a suitable proc...

#!/bin/sh
# the next line restarts using tclsh \
exec tclsh "$0" "$@"
#---------------

package require Gnocl

# args:
# data = list items to be formatted into colums
# nrow = maximum number of rows to produce
# returns
# list of formatted row strings
# note
# tcl only
proc tabulate_Columns {data nrows} {

set r 0 ;# row counter
set str {} ;# list contain final, formatted list, returned by proc

# initialise an array to hold output strings
for {set i 0 } {$i < $nrows } {incr i} { set rows($i) {} }

# build up the output strings
for {set i 0} {$i < [llength $data] } {incr i} {
if {$rows($r) == {} } {
set rows($r) "[lindex $data $i]"
} else {
set rows($r) "$rows($r)\t[lindex $data $i]"
}
incr r
if {$r == $nrows } {set r 0}
}

# insert int the text
for {set i 0 } {$i < $nrows } {incr i} {
lappend str $rows($i)
}

return $str
}

# the uniquitous demo script
set txt1 [gnocl::text]
gnocl::window -child $txt1 -defaultWidth 300 -defaultHeight 100

set data {a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z}

foreach row [tabulate_Columns $data 5] {
$txt1 insert end \t${row}\n
}

No comments: