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
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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
Let’s 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 C’s)
Control structures (1)• if then else 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
}
Control structures (2)• for loops 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
}
Control structures (3)• foreach loops (con't)
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 callAdd 1 ;# Will return 2Add 1 2 ;# Will return 3Add 1 –1 ;# Will return 0
Variable scope• local and global variablesset a 5set b 6set c 7proc var_scope { } { global a set a 3 set b 2 set ::c 1}var_scopeputs "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 listproc sum args {
set s 0foreach 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
• concat : Concatenate two lists– set b [concat [list 1 2 3 4] [list 5 6 7]]– b will be { 1 2 3 4 5 6 7 }
• lappend : Append value at the end of list – By Name– 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
• linsert list index arg1 ?arg2 ... argn? – 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"] )
• lreplace list first last ?arg1 ... argn? – Returns a new list with N elements of listName replaced by the args (set b [lreplace $b 3 5 "AA"
"BB"] )
• lset varName index newValue – The lset command can be used to set elements of a list directly, instead of using lreplace
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.
– 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.
• string wordend string index – 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.
• string wordstart string index – Returns the index of the character just before the first one in the word which contains the
index'th character of string.
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
(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?
– 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