Thursday, June 11, 2009

TCL/TK Tutorial -Part I

Posted on 12:52 PM by SRIRAMAN SRIDHARAN

TCL/TK tutorial for beginners

Introduction:

Tcl (Tool Command Language) is a very powerful but easy to learn dynamic programming language, suitable for a very wide range of uses, including web and desktop applications, networking, administration, testing and many more. Open source and business-friendly, Tcl is a mature yet evolving language that is truly cross platform, easily deployed and highly extensible.

Tk is a graphical user interface toolkit that takes developing desktop applications to a higher level than conventional approaches. Tk is the standard GUI not only for Tcl, but for many other dynamic languages, and can produce rich, native applications that run unchanged across Windows, Mac OS X, Linux and more.

All you have to do is just download the TCL kit release 8.5.7 from

http://tcl.activestate.com/software/tcltk/8.5.html

and start using it. You can also practice all sort of commands provided below in tclsh shell from the downloaded tool kit.

 

 

Chapter-1: Simple Text Output

  1. puts

-         outputs a string in TCL

Example:

1.      puts 1.24

  Output: 1.24

2.      puts hello,world 

Output: hello,world

{Note: words need not be quoted unless it contains a white space in between}

3.      puts {this is a line} (or)      puts “this is a line”

 Output: this is a line

  1. echo

-         echoes the given string

{Note: no need to be quoted even in the presence of white space}

 Example:

1.      echo 5.66

2.      echo hello how are you

  1. #

-         comment lines

-         TCL will ignore the scripts started with ‘#’ symbol. 


Chapter-2: Declaring Variables

  1. set

-          assignment command

Unlike C programming, there is no necessity for declaring different data types such as int, char, float, string, etc.

Syntax:  set

Example:

1.      set  num 10

- assigns 10 to integer variable name ‘num’

2.      set  word  apple

- assigns apple to character variable name ‘word’

3.      set  str  “this is a line”          (or)      set  str  {this is a line}

- assigns the string (this is a line) to variable name ‘str’


Chapter-3: Accessing the variables

1. $

-         represents ‘ value of ’

i.e.,             $x – value of x

                                    $y - value of y 

Syntax: $

Example:

Commands                                                Comments

set  x   “Hello world”                      assigns “Hello World” to variable x

set  y   5.66                                    assigns  5.66  to variable y

puts  $x                                          outputs value of x : Hello world

puts  $y                                          outputs value of y : 5.66

 

Chapter-4: Evaluation & Substitution 

String

Output

Hex Value

\a

Audible Bell

0x07

\b

Backspace

0x08

\f

Form Feed (clear screen)

0x0c

\n

New Line

0x0a

\r

Carriage Return

0x0d

\t

Tab

0x09

\v

Vertical Tab

0x0b

Example:

1.  puts "\nhello \n how are you"

            -prints

                        hello

                        how are you

 2.  puts "Tab\tTab\tTab"

            -prints Tab       Tab      Tab

3.  set x abc

     puts "A simple substitution: $x\n"

            -prints A simple substitution: abc

4.         Commands                                          Comments

        set y [set x "def"]                         

                    puts $y                                                     prints  def

                    puts $x                                                    prints  def


Chapter-5: Mathematical Operations 

1. expr

-         command for using mathematical operations

-         extracted and adapted from the expr man page

-         Test expressions, such as if, while and for loops use expr command internally in order to evaluate the expressions.

2. operators (valid operators are listed below, grouped in decreasing order of precedence)

    1. (-, +, ~,!)

-Unary minus, unary plus, bit-wise NOT, logical NOT. None of these operators may be applied to string operands, and bit-wise NOT may be applied only to integers.

b.  **

- exponentiation (works on both floating-point numbers and integers)

      c. * / %

- Multiply, divide, remainder. None of these operators may be applied to string operands, and remainder may be applied only to integers. The remainder will always have the same sign as the divisor and an absolute value smaller than the divisor. 

            d. + -

- Add and subtract. Valid for any numeric operands.

            e. << >>

- Left and right (bit) shift. Valid for integer operands only.

            f. < > <= >=

- Relational operators: less, greater, less than or equal, and greater than or equal. Each operator produces 1 if the condition is true, 0 otherwise. These operators may be applied to numeric operands as well as strings, in which case string comparison is used.

             g. eq ne in ni

-compare two strings for equality (eq) or inequality (ne). and two operators for checking if a string is contained in a list (in) or not (ni). These operators all return 1 (true) or 0 (false).

Example:

            Commands                                                      Comments

            set X 100                           assigns X value to 100

set Y 200                           assigns Y value to 200

set Z [expr {$Y + $X}]              assigns Z value to 300

puts $Z                             prints value of Z :200

$$

-         Output is obtained after substituting the expression and obtaining result from it

Example:

            Commands                                                      Comments

Set x 1                             assigns value 1 to x

Set y x                             assigns y value as x

Puts [expr $y]                     substitute the value of x as

                                                                        y’s value                                                           

Chapter-6: if Statement

 

Syntax:

if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... ?else? ?bodyN?

Example:

            Commands                                                      Comments

set x 10                  //assigns 10 to value x

if { $x == 10} {          //check the condition whether x is 10

      puts “x is $x”      //execute true condition statements

      } else {                  //if condition fails

            puts “x is not $x”  //execute false condition statements

   }

Chapter-7: Switch Statement

-         Switch commands are used when you want to match a variable against several possible values, and don't want to do a long series of if... elseif ... elseif statements.

 Syntax:

switch string pattern1 body1 ?pattern2 body2? ... ?patternN bodyN?

 

Example:

            Commands                                                                  Comments     

set x 1                             assigns value 1 to x

set y 2                             assigns value 2 to y

set z 3                             assigns value 3 to z

switch $y {                         switch to case $y i.e.,2

            1 {  

                  puts “one”

            }

            2 {

                  puts “two”        prints two as output   

            }

            3 {

                  puts “three”

            }

            default {

                  puts “none”

            }

      }

 

                                Chapter-8:While Statement

 

-         The while command evaluates test as an expression. If test is true, the code in body is executed. After the code in body has been executed, testis evaluated again.

Syntax:

                while test body

Example:

            Commands                                                                  Comments     

Set x 1                       assigns value 1 to x

while {$x < style="mso-tab-count:3">             while value of x is less than 5

puts "x is $x"                output x value

set x [expr {$x + 1}]         increment x value

}


Chapter-9: for Loop

-         It has four arguments; an initialization, a test, an increment/decrement, and the body of code to evaluate on each pass through the loop.

-         It is very similar to for loop used in C programming.

Syntax:

 for start test next body

 

Example:

                        Commands                                                                  Comments     

for {set i 0} {$i < style="mso-tab-count:1">       initialization of for loop

   puts "value of i is: $i"               prints value of i

}


Chapter-10: proc Command

-         The proc command creates a new command.

Syntax:

proc name args body

-         When proc is evaluated, it creates a new command with name name that takes arguments args. When the procedure name is called, it then runs the code contained in body.

Example:

1.                     Commands                                                                  Comments     

proc sum {arg1 arg2} {                          creates  a command sum

set x [expr {$arg1 + $arg2}];             assign x = arg1+arg2

return $x                                 return value of x

}

puts " The sum of 2 + 3 is: [sum 2 3]\n\n"      function call

 

2.

proc example {first {second ""} args} {

if {$second eq ""} {

            puts "There is only one argument and it is: $first"

return 1

      } else {

if {$args eq ""} {

            puts "There are two arguments - $first and $second"

return 2

            } else {

      puts "There are many arguments - $first and $second and $args"

return “many”

}

      }

}

 set count1 [example ONE]

 set count2 [example ONE TWO]

set count3 [example ONE TWO THREE ]  

set count4 [example ONE TWO THREE FOUR]  

No Response to "TCL/TK Tutorial -Part I"