Use for_file to Ease Line-by-Line Processing

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.


2 thoughts on “Use for_file to Ease Line-by-Line Processing

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s