0% found this document useful (0 votes)
114 views60 pages

TCL and TK

TCL and TK provide the ability for applications to communicate with each other. TCL is a general purpose scripting language used to build GUIs with TK, a cross-platform widget toolkit. The document discusses setting up a local environment for TCL, executing TCL programs, special variables in TCL, flow control commands like if/else, while, for, foreach, and strings, files, patterns and regular expressions in TCL.

Uploaded by

Ganesh Nimmala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views60 pages

TCL and TK

TCL and TK provide the ability for applications to communicate with each other. TCL is a general purpose scripting language used to build GUIs with TK, a cross-platform widget toolkit. The document discusses setting up a local environment for TCL, executing TCL programs, special variables in TCL, flow control commands like if/else, while, for, foreach, and strings, files, patterns and regular expressions in TCL.

Uploaded by

Ganesh Nimmala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

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

Examples for using Tcl special variables

• 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

• A string is a sequence of characters. String in Tcl, unlike in other


languages, need not be always enclosed within double quotes. They are
necessary only if we have a space between words. Tcl is a string based
language. It provides a rich set of commands for manipulating strings.
• Puts tcl
• puts java
• puts Falcon
• puts “Tcl language”
• puts {Tcl language}
output
• Strings in Tcl do not have to be always enclosed within quotes.
• Strings in Tcl can be grouped with double quotes or curly brackets.

T cl
Java
Falcon
Tcl Language
Tcl Language
Multiline strings

set lyrics “ I am a student of


CMRCET Btech 3 rd year IT Department
My roll number is 12”
puts $lyrics
Multiline strings

• Multiline strings
Comparing strings

• Basic comparision of strings can be done with the string compare


command
puts [string compare 12 12]
puts [string compare Eagle Eagle]
puts [string compare Eagle eagle]
puts[string compare –nocase Eagle eagle]
output
• 0
• 0
• -1
• 0
patterns
• The "regexp" command is used to match a regular expression in Tcl. A
regular expression is a sequence of characters that contains a search
pattern. It consists of multiple rules and the following table explains these
rules and corresponding use.
Sr.No. Rule & Description
1 x
Exact match.
2 [a-z]
Any lowercase letter from a-z.
3 .
Any character.
4 ^
Beginning string should match.
5 $
Ending string should match.
6 \^
Backlash sequence to match special character
^.Similarly you can use for other characters.
Syntax
• The syntax for regex is given below −
regexp patterns searchString fullMatch subMatch1….subMatchn

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

• open filename accessmode


• Here , filename is string literal, which you will use to name your file
and accessMode 
Acess Mode
Sr.No. Mode & Description
1 r
Opens an existing text file for reading purpose and the file must exist. This is the default
mode used when no accessMode is specified.
2 w
Opens a text file for writing, if it does not exist, then a new file is created else existing file
is truncated.
3 a
Opens a text file for writing in appending mode and file must exist. Here, your program
will start appending content in the existing file content.

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.

set fp [open “input.txt” w+]


puts $fp “test”
close $fp
Reading a File

set file_data[ read $fp]


A complete example of read and write is shown below −

set fp [open “input.txt” w+]


puts $fp “test”
close $fp
set fp[open “input.txt” r]
set file_data[read $fp]
puts $file_data
close $fp Output: test
eval
• eval - Evaluate a Tcl script

• 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.

Note that either concat or list may be used to create the command string,


but that these two commands will create slightly different command strings.
eval arg1 ??arg2?? ... ??argn??

Evaluates arg1 - argn as one or more Tcl commands.


The args are concatenated into a string, and passed to tcl_Eval to evaluate and execute.

Eval returns the result (or error code) of that evaluation.


Source comand

• source - Evaluate a file or resource as a Tcl script

• This command takes the contents of the specified file or resource and


passes it to the Tcl interpreter as a text script.
• The return value from source is the return value of the last command
executed in the script.
source fileName
source -rsrc resourceName ?fileName?
source -rsrcid resourceId ?fileName?
Up level Command
• Uplevel returns the result of that evaluation.
• If level is an integer then it gives a distance (up the procedure calling
stack) to move before executing the command.
• If level consists of # followed by a number then the number gives an
absolute level number. If level is omitted then it defaults to 1.
• uplevel ? level?arg?arg…?
Name Space
• A namespace is a collection of commands and variables.
• It encapsulates the commands and variables to ensure that they won't
interfere with the commands and variables of other namespaces.
• Tcl has always had one such collection, which we refer to as the global
namespace.
Creating Namespace

#!/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

ErrorMsg: Error generated by error


ErrorCode: 401
ErrorInfo: Info String for error
(procedure "Div" line 1)
invoked from within
"Div 10 0“
Result = 5
Event Driven Programs
• Most programs and devices like a cellphone respond to events — things
that happen. For example, you might move your mouse, and the
computer responds. Or you click a button, and the program does
something interesting.
Tcl commands relevant to event-driven programming

• after : doing some action after some event


• update: updating after or before some event
• vwait : enters the event loop and modifies the variable
• fileevent: binds a script to a file event

You might also like