TCL and TK
TCL and TK
UNIT 5
What is TCL
• Tcl is a general purpose multi-paradigm system programming language. It
is a scripting language that aims at providing the ability for applications to
communicate with each other. On the other hand, Tk is a cross platform
widget toolkit used for building GUI in many languages. This tutorial
covers various topics ranging from the basics of the Tcl/Tk to its scope in
various applications.
Local Environment Setup
• If you are willing to set up your environment for Tcl, you need the
following two software applications available on your computer −
• Text Editor
• Tcl Interpreter.
• Text Editor
• This will be used to type your program. Examples of a few text editors include
Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
• Name and version
• The Tcl Interpreter
• It is just a small program that enables you to type Tcl commands and have them
executed line by line. It stops execution of a tcl file, in case, it encounters an error
unlike a compiler that executes fully.
How to execute TCL Program
• C:\Tcl>tclsh helloworld.tcl
• C:\Tcl>helloworld
TCL Special Variables
• In Tcl, we classify some of the variables as special variables and they have
a predefined usage/functionality. The list of specials variables is listed
below.
Sr.No. Special Variable & Description
1 argc
Refers to a number of command-line arguments.
2 argv
Refers to the list containing the command-line arguments.
3 argv0
Refers to the file name of the file being interpreted or the name by which we invoke the script.
4 env
Used for representing the array of elements that are environmental variables.
5 errorCode
Provides the error code for last Tcl error.
6 errorInfo
Provides the stack trace for last Tcl error.
7 tcl_interactive
Used to switch between interactive and non-interactive modes by setti
#!/usr/bin/tclsh puts $tcl_version
• Tcl version
• #!/usr/bin/tclsh
puts $tcl_version
Output:
8.6
• Tcl Environment Path
#!/usr/bin/tclsh
Puts $env(PATH)
Output
/home/cg/root/GNUstep/Tools:/usr/GNUstep/Local/Tools:/usr/GNUstep/ System/Tools:
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/webmaster/.local/bin:/ home/webmaster/bin:/usr/local/
scriba/bin:/usr/local/smlnj/ bin:/usr/local/bin/std:/usr/local/bin/extra:/usr/local/fantom/bin:/usr/ local/dart/bin:/usr/bin:/usr/local/
bin:/usr/local/sbin:/usr/sbin:/opt/mono/ bin:/opt/mono/lib/mono/4.5:/usr/local/bin:.:/usr/libexec/sdcc:/usr/local/ icon-v950/bin:/usr/
local/mozart/bin:/opt/Pawn/bin:/opt/jdk1.7.0_75/bin:/ opt/jdk1.7.0_75/jre/bin:/opt/pash/Source/PashConsole/bin/Debug/
First TCL program
• #!/usr/bin/tclsh
puts “Hello World”
Flow Control in TCL
• The if command
•
The switch command
•
The while command
•
The for command
•
The foreach command
•
The break and continue commands
The if command
if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... ?else? ?bodyN?
If command
#!/usr/bin/tclsh
set stud female
if {$stud == "male"}{
puts "It is a boy" }
else {
puts "It is a girl" }
• #!/usr/bin/tclsh
#switch_cmd.tcl
puts “Select a top level domain name:”
gets stdin domain
switch $domain{
us{ puts “United States” }
de{ puts “Germany”}
sk{ puts “Srilanka”}
default {puts “unknown”}
}
Output
$ ./switch_cmd.tcl
Select a top level domain name:sk
Slovakia
The while command
• #!/usr/bin/tclsh
#whileloop.tcl
set i 0
set sum 0
while{ $i < 10}
{
incr i
incr sum $i
}
puts $sum
For Command
• #!/usr/bin/tclsh
for { set i 0} {$i < 10} {incr i} {
puts $i
}
output
0
1
2
3
4
5
6
7
8
9
The for each command
• #!/usr/bin/tclsh
set planets {mercury venus earth mars Jupiter Saturn Uranus Neptune }
foreach planet $planets {
puts $planet
}
output
• Mercury
• Venus
• Earth
• Jupiter
• Saturn
• Uranus
• Neptune
The break and continue commands
• #!/usr/bin/tclsh
While true {
set r [expr 1 + round(rand()*30)]
puts “$r”
if { $r ==2} { break }
}
puts “”
output
• 28 20 8 8 12 22
continue
• #!/usr/bin/tclsh
set num 0
while{ $num < 100 } {
incr num
if {$num %2 ==0} { continue }
puts “$num”
}
puts “”
Strings in Tcl
• Multiline strings
Comparing strings
Here, Patterns are the rules as mentioned earlier. Search string is the actual
string on which the regex is performed. Full match is any variable to hold the
result of matched regex result. Submatch1 to SubMatchn are optional subMatch
variable that holds the result of sub match patterns.
• #!/usr/bin/tclsh
regexp {([A-Za]*)} “Tcl Tutorial” a b
puts “Full Match: $a”
puts “Sub Match1:$b”
output
• Full Match :Tcl
• Sub Match1: Tcl
Multiple Patterns
• The following example shows how to search for multiple patterns. This is example
pattern for any alphabets followed by any character followed by any alphabets.
#!/usr/bin/tclsh
regexp {([A-Za-z]*).([A-Za-z]*)} “Tcl Tutorial” a b c
puts “Full Match :$a”
puts “Sub Match1: $b”
puts “Sub Match2: $c”
Files in TCL
• Tcl supports file handling with the help of the built in commands
• open,
• read,
• puts,
• gets, and
• close.
Opening Files
4 r+
Opens a text file for reading and writing both. File must exist already.
5 w+
Opens a text file for reading and writing both. It first truncate the file to zero length if it
exists otherwise create the file if it does not exist.
6 a+
Opens a text file for reading and writing both. It creates the file if it does not exist. The
reading will start from the beginning, but writing can only be appended.
Closing a File
• close filename
• Writing a file
puts command is used to write to an open file
puts $filename “text to write”
A simple example for writing to a file is shown below.
• Eval concatenates all its arguments in the same fashion as the concat
command, passes the concatenated string to the Tcl interpreter recursively,
and returns the result of that evaluation (or any error generated by it).
The eval command will evaluate a list of strings as though they were
commands typed at the % prompt or sourced from a file.
The eval command normally returns the final value of the commands being evaluated.
If the commands being evaluated throw an error (for example, if there is a syntax error
in one of the strings), then eval will will throw an error.
#!/usr/bin/tclsh
namespace eval MyMath {
# Create a variable inside the namespace
variable myResult
}
# Create procedures inside the namespace
proc MyMath::Add {a b } {
set ::MyMath::myResult [expr $a + $b]
}
MyMath::Add 10 23
puts $::MyMath::myResult
OUTPUT
• 33
Nested Namespaces
#!/usr/bin/tclsh
namespace eval MyMath {
# Create a variable inside the namespace
variable myResult
}
namespace eval extendedMath {
# Create a variable inside the namespace
namespace eval MyMath {
# Create a variable inside the namespace
variable myResult }
}
set ::MyMath::myResult "test1" puts $::MyMath::myResult set ::extendedMath::MyMath::myResult "test2"
puts $::extendedMath::MyMath::myResult
Output
• test1
• test2
• Error handling in Tcl is provided with the help of error and catch commands.
The syntax for each of these commands is shown below.
• Error Syntax:
error message info code
• Catch Syntax
catch script resultVarName
#!/usr/bin/tclsh
proc Div {a b} {
if {$b == 0} {
error "Error generated by error" "Info String for error" 401
} else {
return [expr $a/$b]
}
}
if {[catch {puts "Result = [Div 10 0]"} errmsg]} {
puts "ErrorMsg: $errmsg“
puts "ErrorCode: $errorCode“
puts "ErrorInfo:\n$errorInfo\n"
}
if {[catch {puts "Result = [Div 10 2]"} errmsg]} {
puts "ErrorMsg: $errmsg"
puts "ErrorCode: $errorCode"
puts "ErrorInfo:\n$errorInfo\n“
}
Output