270 likes | 391 Vues
Tcl (Tool Command Language) is an interpreted scripting language that enables easy programming and command execution at runtime. It is embeddable, platform-independent, and often used alongside Tk, its GUI toolkit that provides various widgets for user interface development. Tcl/Tk's simplicity and vast online resources make it an ideal choice for scripting and application development. Many major applications, such as Ns2 and Mentor Graphics, utilize Tcl for interface design. This tutorial covers syntax, command structures, mathematical expressions, and list operations in Tcl.
E N D
Tcl/TkTutorial Dongsoo S. Kim dskim@iupui.edu
What is Tcl/Tk? • Tcl: Tool Command Language • Interpreted programming (scripting) language • Build on-the-fly commands and procedures • Embeddable • Platform-independent • Tk: • GUI toolkit and widgets based on Tcl • Open source, cross-platform
Why Tcl/TK? • Easy and fast programming • Free • Lots of online documentation, mostly free • Resources • http://www.tcl.tk • Major applications use the Tcl as their interfaces: • Ns2 • Mentor Graphics
Hello World % tcl tcl>puts "Hello. World!" Hello. World! tcl>exit %
Script File • Start the Tcl program followed by a filename containing the script. % cat hello.tcl puts "Hello. World!" % tcl hello.tcl Hello. World! %
Script as a Program • A script text file can be considered as a program if • it is an executable file, and • its first line contains a full path name of the tcl program following “#!” % ls -l -rwxr-xr-x 1 user group 42 Jul 3 13:12 hello.tcl % which tcl /usr/local/bin/tcl % cat hello.tcl #!/usr/local/bin/tcl puts "Hello. World!" % hello.tcl Hello. World! %
Tcl Syntax • Simple syntax • command_name arg1 arg2 … • Print to screen (puts) puts –nonewline"Hello. " puts "World!" • Assignment (set) set income 32000 puts "The income is $income" • Use '$' to get the value of a variable (R-value)
Comments • A line started with a pond sign(#) is ignored as comments until the end of the line • A command can be followed by a comment in a line with by placing ;# • Exception • #! at the first line indicates the script program • It is a Unix rule, but not a Tcl rule # the first script puts –nonewline"Hello. " ;# continuing puts "World!“
Multiple Commands in a Line • A Tcl command is terminated by an invisible new line character, or • A semicolon(;) can be used to explicitly terminate a command tcl>puts "Hello. "; puts "World! " hello world
A Command Stretched to Lines • A command can be stretched to multiple lines by using backslashes (\) • The backslash and a following new line character is ignored • Note: There must not be any characters (even space characters) between the backslash and the new line character tcl>puts -nonewline \ =>"Hello. World!" Hello. World!tcl>
Mathematical Expression Tcl>set pi 3.141592 Tcl>set r 2 Tcl>expr 2*$pi*$r 12.566368 Tcl>expr sin($pi/3) 0.866025294853 • Mathematical expression command (expr) • Operators • arithmetic (+, -, *, /, %) • Bitwise (~, <<, >>, &, ^, |) • Logical (!, &&, ||) • Boolean (<, >, <=, >=, ==, !=) • String Boolean (eq, ne, <, >, <=, >=) • List containment (in, ni) • Ternary (x?y:z) • Math functions (log, sin, cos, …)
Sub-Command Evaluation tcl>set a 3.0 tcl>set b $a+4 tcl>puts $b 3.0+4 tcl>set c [expr $a+4] tcl>puts $c 7.0 • A Tcl command in a Tcl command: []
Control Structures (if) set sel 3 if {$sel == 1} { puts "Selection $sel" } elseif {$sel == 2} { puts "Selection $sel" } else { puts "Invalid selection" } • if {cond} {commands}[ elseif {cond} {commands} …][ else {commands} ]
Control Structures (while) set i 1 set sum 0 while {$i <= 10} { set sum [expr $sum+$i] incri } while {cond} {commands}
Control Structures (for) puts "Fahrenheit\tCelcius" for {set fahr 0} {$fahr < 100} {incrfahr} { set celc [expr 5*($fahr-32)/9] puts "$fahr\t\t$celc" } Fahrenheit Celcius 0 -18 1 -182 -17 … for {init} {term} {incr} {statements}
Control Structures (foreach) • Basic foreachset weekdays {Sun Mon Tue Wed Thu Fri Sat}foreach d $weekdays { puts $d} • foreach Variationsset Colors {red orange yellow green blue purple}foreach {a b c} $Colors { puts "$c--$b--$a“}set Foods {apple orange banana lime berry grape}foreach f $Foods c $Colors { puts "a $f is usually $c" } foreach {a b} $Foods c $Colors { puts "$a & $b are foods. $c is a color." }
Procedures proc mile2km dist { return [expr $dist*1.6] } puts "Miles \t KM" for {set d 1} {$d < 10} {incr d} { set km [mile2km $d] puts "$d\t $km" } • Called by value only • Syntaxprocname arg-list proc-body
Variable scope • 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" By default, all variables in a procedure are local. To access the variable outside of the scope, use the command “global”.
Lists in Tcl • set my_list [list a b c] set my_list "a b c " set my_list {a b c} An ordered collection of elements A string containing any number of elements separated by white spaces (space or tab characters). For example, Sun Mon Tue Wed Thu Fri Satis a list with four element. To save a list to a variable
List Operations concat – join multiple list into a single list join – concatenate list elements into a string lappend – append elements to an existing list lindex – return an indexed element from a list linsert – insert an element to an existing list list – create explicitly a list from values llength – return the number of elements in a list lrange – return a sub-list from a list lreplace – return a new list after replacing elements lsearch – return the index of a searching pattern lsort – sort the list split – return a list by splitting a string by a split-char.
List Operations, Example set weekday [list “Mon” “Tue” “Wed” “Thu” “Fri”] set weekend {Sat Sun} set week [concat $weekday $weekend] puts $week • Mon Tue Wed Thu Fri Sat Sun lindex $week 0 • Mon • lindex $week end • Sun • llength $weekday • 5
Lists of lists (of lists…) set a [list [list x y z]] puts [lindex $a 0] puts [lindex [lindex $a 0] 1] puts [lindex [lindex $a 1] 0] (unexpected result) set a [list x [list [list y] [list z]]] => How to get to the z? set arg1 [list g [list f [list h [list i X]]] [list r Y] k] set arg2 [list g [list f [list h [list i Y]]] [list r b] L] set both [list $arg1 $arg2] puts $both
Array operations Associative arrays (string as index) set color(rose) red set color(sky) blue set color(medal) gold set color(leaves) green set color(blackboard) black puts [array exists color](tests if an array with the name "color" exists) puts [array exists colour] puts [array names color] (returns a list of the index strings) 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)
Regular expressions • regsubset stmt "Fan is one of Shania’s fans" regsub –nocase"fan" $stmt "Kristy"newStmt ?switches? exp string subSpec ?varName? puts "$newStmt" regsub –nocase –all "fan" $stmt "Kristy"newStmt puts "$newStmt" • regexp(returns 1 if the regular expression matches the string, else returns 0) puts [regexp –nocase"fan" $stmt] ?switches? regexp string • format puts [format "%s is a %d-year-old" Fan 26] formatString ?argarg ...?
String operations set statement " Fan is a student " set statement [string trim $statement] puts [string length $statement] puts [string length statement] puts [string index $statement 4] puts [string index $statement end] puts [string first"is" $statement] (string last) puts [string first $statement "is"] puts [string range $statement 4 end] puts [string replace $statement 9 end "professor"] puts [string match"*student" $statement] (* ? [])
File Operations set fRead [open source.txt r] set fWrite [open target.txt w] while {![eof $fRead]} { set strLine [gets $fRead] ;#or gets $fReadstrLine regsub –nocase –all "fan" $strLine"kristy" strLine puts $fWrite $strLine } close $fRead close $fWrite ################ source.txt ################ Fan is a CSE student. Fan is also one of Shania’s fans. Kristy and Fan are classmates.
Miscellaneous commands • eval: execute a command dynamically built up in your program set Script { set Number1 17 set Number2 25 set Result [expr $Number1 + $Number2] } eval $Script • exec: execute external programs • clock • trace • info • after