What is TCL?
Tool Command Language An interpreted programming language
Created by John Ousterhout. Intended to be embedded with application. But used in rapid prototyping, scripting, GUI, testing of SW.
Platform-independent All operations are commands, including language structures. Everything can be dynamically redefined and overridden. All data types can be manipulated as strings. Need little experience with programming
Easy Programs are short, efficient
Lets Code
Hello world puts "Hello, world! How to run program? Tclsh interactive mode Tclsh prog.tcl Double click .tcl file
Constants
In Tcl, all free constants are strings abc is the same as abc 5 is the same as 5 <, >, == ,<= and >= compare numerically If any of the arguments are non-numbers, errors are thrown Strings can also be compared literally: string compare string1 string2
Variable
A Tcl variable is a C-style name, which satisfies the regular expression: {[A-Za-z_][A-Za-z_0-9]*} Examples: iterator loopInit _ErrorCount76 Non-examples: 78Cool ~notAVariable
Variables (cont..)
set command Usage: set <varname> <value> Example: set a 5 puts $a (puts = putString exactly like Cs) Will print out 5
How TCL works
Handling Commands
Argument Processing
Grouping
White spaces vs {}
Substitution
Variable substitution $varName Command substitution [aCommand arg1 arg2 ]
Command Execution
Example 1
command1 abc 123 xyz 456 command2 {abc 123} xyz 456
command3 abc 123 $xyz 456
command4 abc 123 [anotherCommand xyz 456]
Example 2
proc PrintList {aList} { foreach anItem $aList { puts $anItem } } set ITEM1 item1 Set ITEM2A item2a PrintList item0 $ITEM1 {$ITEM2A item2b}
TCL vs Other shells
Grouping precedes substitution in TCL only csh> setenv GARGS -i word file.txt csh> grep $GARGS tclsh% set ARGS {ab aabb m} tclsh% regexp $ARGS wrong # args: should be "regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...?"
Basic operations
print to screen (puts) puts nonewline "Hello, world!" puts "!!" assignment (set) set income 32000 puts "income is $income" mathematical expressions (expr) set a 10.0 expr $a + 5 expr int($a/3)
Some useful commands
unset: destroy a variable
unset num
info: check whether the named variable has been defined
if {![info exists num]} {
set num 0
} incr num
Comments
# : single-line comments, similar to "//" in C ;# : in-line comments, just like "//" in C
User Input
Command line argc no of command line arguments argv0 program name argv list of command line arguments
User input set userName [gets stdin] gets stdin inlinevar
Operators
Unary (- + ~ !) :
Unary minus, unary plus, bit-wise NOT, logical NOT
+-*/%:
Add, Subtract, Multiply, divide, remainder
** :
Exponentiation
<< >> :
Left and right (bit) shift
Comparison operators
Numbers : < > <= >= String : eq ne in ni (string compare str1 str2)
Bitwise (& | ^ ~):
Bitwise and, or, exclusive or, not
Logical (&& || !):
Logical and, or, not
if then else
Control structures (1)
set income 32000 if {$income > 30000} { puts "$income -- high" } elseif {$income > 20000} { puts "$income -- middle" } else { puts "$income -- low" }
while loops
set i 0 while {$i < 100} { puts "I am at count $i" incr i }
for loops
Control structures (2)
for {set i 0} {$i < 100} {incr i} {
puts "I am at count $i and going up"
} for {set i 100} {$i > 0} {incr i -1} { puts "I am at count $i and going down" }
foreach loops
set lstColors {red orange yellow green blue purple}
foreach c $lstColors { puts $c }
foreach loops (con't)
Control structures (3)
set lstColors {red orange yellow green blue purple} foreach {a b c} $lstColors { puts "$c--$b--$a" } set lstFoods {apple orange banana lime berry grape} foreach f $lstFoods c $lstColors { puts "a $f is usually $c" } foreach {a b} $lstFoods c $lstColors { puts "$a & $b are foods. $c is a color." }
Procedures
procedure calls (embedded commands)
set b [expr $a + 5] puts "The value of b is $b"
create your own procedure (called by value only)
proc foo {a b c} { return [expr $a * $b - $c] } puts [expr [foo 2 3 4] + 5] proc bar { } { puts "I'm in the bar procedure" } bar
Procedures (default value)
Optional Parameters are very easy to set up in Tcl By Example:
proc Add { number {by 1} } { return [expr $number+$by] }
The variable by takes on a default of 1 unless specified otherwise in the function call
Add 1 Add 1 2 Add 1 1 ;# Will return 2 ;# Will return 3 ;# Will return 0
Variable scope
local and global variables
set a 5 set b 6 set c 7 proc var_scope { } { global a set a 3 set b 2 set ::c 1 } var_scope puts "The value for a b c is: $a $b $c"
Procedures (variable args)
Variable length arguments supported by args keyword which can be placed at the end of argument list
proc sum args { set s 0 foreach i $args { incr s $i } return $s } sum 1 2 3 4 5
List
Many ways to create a list
set myList [list a b c]
set myList "a b c" set myList {a b c} set lst [split "item 1.item 2.item 3" "."]
Retrieving an element within a list: lindex lindex is 0-based, just like C
set b [lindex $a 3] set b [lindex $a end]
List operations
llength : Return the length of a list
llength [list 1 2 3] will be 3 llength [list] will be 0 set b [concat [list 1 2 3 4] [list 5 6 7]] b will be { 1 2 3 4 5 6 7 } set a [list 1 2 3] lappend a 4 Now a will be { 1 2 3 4 } Note: lappend takes a list Name, not a list Returns a new list with the new list elements inserted just before the index th element of listName (set b [linsert $a 3 "1 2 3"] ) Returns a new list with N elements of listName replaced by the args (set b [lreplace $b 3 5 "AA" "BB"] ) The lset command can be used to set elements of a list directly, instead of using lreplace
concat : Concatenate two lists
lappend : Append value at the end of list By Name
linsert list index arg1 ?arg2 ... argn?
lreplace list first last ?arg1 ... argn?
lset varName index newValue
List operations
lsearch list pattern
Searches list for an entry that matches pattern, and returns the index for the first match, or a -1 if there is no match. By default, lsearch uses "glob" patterns for matching.
lsort list
Sorts list and returns a new list in the sorted order.
lrange list first last
Returns a list composed of the first through last entries in the list.
String subcommands (1)
string match (uses glob patterns)
# Matches string match f* foo # Matches string match f?? foo # Doesn't match string match f foo
string length string
Returns the length of string.
string index string index
Returns the indexth character from string.
string range string first last
Returns a string composed of the characters from first to last.
String subcommands (2)
string compare string1 string2
Compares string1 to string2 and returns:
-1 ..... If string1 is less than string2 0 ........ If string1 is equal to string2 1 ........ If string1 is greater than string2
string first string1 string2
Returns the index of the character in string1 that starts the first match to string2, or -1 if there is no match. (set first [string first "/" $path]; returns index of first / in $path )
string last string1 string2
Returns the index of the character in string1 that starts the last match to string2, or -1 if there is no match.
Returns the index of the character just after the last one in the word which contains the index'th character of string. A word is any contiguous set of letters, numbers or underscore characters, or a single other character. Returns the index of the character just before the first one in the word which contains the index'th character of string.
string wordend string index
string wordstart string index
String subcommands (3)
string tolower string
Returns string with all the letters converted from upper to lower case.
string toupper string
Returns string with all the letters converted from lower to upper case.
string trim string ?trimChars?
Returns string with all occurrences of trimChars removed from both ends. By default trimChars are whitespace (spaces, tabs, newlines). Note that the characters are not treated as a "block" of characters - in other words, string trim "davidw" dw would return the string avi and not davi.
string trimleft string ?trimChars?
Returns string with all occurrences of trimChars removed from the left. By default trimChars are whitespace (spaces, tabs, newlines)
string trimright string ?trimChars?
Returns string with all occurrences of trimChars removed from the right. By default trimChars are whitespace (spaces, tabs, newlines)
format formatString ?arg1 arg2 ... argN?
(printf in C) set price4 [format "%-20s %10.2f per Lb." Steak 3.59997]
Array operations
Associative arrays (string as index)
set color(rose) red set color(sky) blue set color(medal) gold puts [array exists color] (tests if an array with the name "color" exists) puts [array names color] (returns a list of the keys) foreach item [array names color] { puts "$item is $color($item)" } (iterating through array) set lstColor [array get color] (convert array to list) array set color $lstColor (convert list to array) array size arrayName Returns the number of elements in array arrayName array unset arrayName ?pattern? Unsets all of the elements in the array. If pattern exists, only the elements that match pattern are unset.
File Handling
The simplest methods to access a file are via gets and puts. Sometimes more efficient to use the read command to load an entire file, and then parse the file into lines with the split command. open fileName ?access?
access can be r, r+, w, w+, a, a+
set fRead [open source.txt r] set fWrite [open target.txt w] while {![eof $fRead]} { set strLine [gets $fRead] ;#or gets $fRead strLine regsub nocase all "fan" $strLine "kristy" strLine puts $fWrite $strLine } close $fRead close $fWrite
File Handling (cont..)
read ?-nonewline? fileID
Reads all the remaining bytes from fileID, and returns that string. If -nonewline is set, then the last character will be discarded if it is a newline. Any existing end of file condition is cleared before the read command is executed.
read fileID numBytes
Reads up to numBytes from fileID, and returns the input as a Tcl string.
seek fileID offset ?origin?
Change the current position within the file referenced by fileID. Origin can be start, current, end
tell fileID
Returns the position of the access pointer in fileID as a decimal string. Count the no of line in file
# gets with two arguments returns the length of the line, # -1 if the end of the file is found
while { [gets $infile line] >= 0 } { incr number } close $infile
More
TCL Guide www.ActiveState.com