In my job, I often need to open a file, read and process each line until the end. In Tcl, that pattern can be translated as:
set infile [open file.txt r]
while {[gets $infile line] >= 0} {
# do something with $line...
}
close $infile
Simple? Yes, but I can still see room for improvements. The Tclx package has a for_file command which can simplify the coding quite a bit:
package require Tclx
for_file line file.txt {
# do something with $line...
}
Not only I don’t have to worry about openning and closing the file, I don’t have to deal with the lengthy while/gets command, which can be error-prone. Finally, the second construct is much cleaner and easier to understand.
After learning about the for_file command, I discovered that the fileutil package also has a similar command:
package require fileutil
fileutil::foreachLine line file.txt {
# do something with $line...
}
It seems either one of them will get the job done. Personally, I prefer the for_file command because it is shorter. If you are aware of any differences between the two, please comment.

You surely meant fileutil::foreachLine rather?
Comment by Zbigniew — June 3, 2009 @ 12:02 am
Thank you Zbigniew, I did mean fileutil::foreachLine instead of fileutil::foreachLine.
Comment by Hai — June 3, 2009 @ 10:04 pm