Version 3 of The filter idiom

Updated 2003-07-09 16:11:00

Richard Suchenwirth 2003-07-09 - After having written the following code repeatedly, I just declare it to be an idiom. The filter functionality is frequently seen on Unix (and even DOS) tools, and I think was published in the Software Tools book:

  • read from stdin (or files specified on command line)
  • write to stdout

Such tools (grep, sed, awk, sort, ...) can easily be combined ("glued") in pipes to do powerful things. A little framework for Tcl scripts with the filter functionality:

 set about "usage: myFilter ?file...?

 Does something meaningful with the specified fiules, or stdin.
 "

 #-- This handler contains the real functionality for one stream (or file)
 proc myHandler channel {
   ...
 }
 #-- This prevents lengthy errors if a filter|more is terminated with 'q'
 proc puts! string {catch {puts stdout $string}}

 if {[lsearch $argv "--help"]>=0} {puts $about; exit}

 if {[llength $argv]==0} {
    puts! [myHandler stdin]
 } else {
        foreach file $argv {
            set fp [open $file]
            puts! [myHandler $fp]
            close $fp
        }
 }

Arts and crafts of Tcl-Tk programming