Tcl - a new example for data reformatting
Archive - Originally posted on "The Horse's Mouth" - 2015-10-10 06:23:31 - Graham EllisTcl is an excellent language for combing through and reformatting data - though rarely a first choice language for such tasks if users aren't doing other things with it too.
Towards the end of last week's Learning to program in TCL course, a "side task" requirement came up to reformat our course diary into a .csv file so that a reseller who sells our courses to fill gaps / niches in his own more generic schedule.
Data of the form
30,11,2015 EL 8
needs to be transformed into data of the form
ELFULL,30/11/2015,09:00,04/12/2015,17:00,Standard,1,1,SN12 7NY,En-GB,1350,1350,GBP,Well House,Learning to Program in Perl,Other (IT)Code
Complete program [here] and sample data [here].
The main code is as simple as
loadDataWH "diary" intoHere
saveDataQA "qa.csv" intoHere
so you can see that even in Tcl, we're using good, structured programming techniques - in this case letting me provide a number of different input formats and a number of output genereators.
Other points of note ...
• calculating end date from start date, allowing for month and year ends:
set starts [clock scan "$day,$month,$year 12 00" -format "%d,%m,%Y %H %M"]
set ends [expr $starts + ($courselength -1) * 3600 * 24]
set eday [clock format $ends -format %e]
set emonth [clock format $ends -format %m]
set eyear [clock format $ends -format %Y]
reduces day, month, year of start to seconds from 1.1.1970, adds the number of days of the course (*3600*24) to make it seconds, and converts back. Much easier than trying to work out month lengths, especially for February in leap years.
• course names ending in "P" are 4 days and "L" are five days:
set courselength 5
set courseformat {Learning to Program in %s}
if {[regexp {P$} $coursecode]} {
set courselength 4
set courseformat {%s Programming}
}
• use of upvar to pass big chunks of data out of and into procs effectively and easily.
• allowing blank lines on input to be ignored
if {[string length $lyne] < 1} continue
• ... and many other useful techniques, worth a study!