TCL

puts

format

set

expr

string

while

incr

proc

specify a literal dollar sign, brace, or bracket as :

set dollar \$foo

how to run:

change to ns prompt %

% source file_name.tcl

creating a Tcl script

In UNIX you can start a file with

#!/usr/local/bin/tclsh

Tcl Procedures

The main part of the program is a procedure named procedure. This procedure takes one argument, arg, that is the name of a file or directory.

proc procedure {arg}

{

# Prodedure body here

}

The arg parameter is set when the procedure procedure is called. If you called Dos2Unix like this:

Dos2Unix myfile.txt

then the arg parameter gets the value myfile.txt when executing inside procedure.

Command Line Arguments

For our program, we want to pass the names of the files to process on the UNIX command line (i.e., when you are invoking the problem from Bash or Cshell). Command line arguments are stored in the argv variable. The foreach loop at the end of the script calls procedure with each file given on the command line:

foreach f $argv { procedure $arg }

Testing Conditions

if {[file isdirectory $arg]}

{

# Process the directory

}

else

{

# Process one file

}

Looping over a list of values

foreach g [glob [file join $arg *]]

{

procedure $g

}

Working with Files

set in [open $arg]

set out [open $arg.new w]

Reading and writing the files is done in one combination of commands:

puts -nonewline $out [read $in]

When we are done with the files, we must close the channels.

close $in close $out

file rename -force $f.new $f

This reads from the standard input channel, stdin, and writes

to the standard output channel, stdout.

puts -nonewline stdout [read stdin]

Here is a loop that reads the file in blocks of 32 Kbytes

set blocksize [expr 32 * 1024]

while {![eof stdin]} {

puts -nonewline stdout [read stdin $blocksize]

}