Tcl – Lists ”; Previous Next List is one of the basic data-type available in Tcl. It is used for representing an ordered collection of items. It can include different types of items in the same list. Further, a list can contain another list. An important thing that needs to be noted is that these lists are represented as strings completely and processed to form individual items when required. So, avoid large lists and in such cases; use array. Creating a List The general syntax for list is given below − set listName { item1 item2 item3 .. itemn } # or set listName [list item1 item2 item3] # or set listName [split “items separated by a character” split_character] Some examples are given below − Live Demo #!/usr/bin/tclsh set colorList1 {red green blue} set colorList2 [list red green blue] set colorList3 [split “red_green_blue” _] puts $colorList1 puts $colorList2 puts $colorList3 When the above code is executed, it produces the following result − red green blue red green blue red green blue Appending Item to a List The syntax for appending item to a list is given below − append listName split_character value # or lappend listName value Some examples are given below − Live Demo #!/usr/bin/tclsh set var orange append var ” ” “blue” lappend var “red” lappend var “green” puts $var When the above code is executed, it produces the following result − orange blue red green Length of List The syntax for length of list is given below − llength listName Example for length of list is given below − Live Demo #!/usr/bin/tclsh set var {orange blue red green} puts [llength $var] When the above code is executed, it produces the following result − 4 List Item at Index The syntax for selecting list item at specific index is given below − lindex listname index Example for list item at index is given below − Live Demo #!/usr/bin/tclsh set var {orange blue red green} puts [lindex $var 1] When the above code is executed, it produces the following result − blue Insert Item at Index The syntax for inserting list items at specific index is given below. linsert listname index value1 value2..valuen Example for inserting list item at specific index is given below. Live Demo #!/usr/bin/tclsh set var {orange blue red green} set var [linsert $var 3 black white] puts $var When the above code is executed, it produces the following result − orange blue red black white green Replace Items at Indices The syntax for replacing list items at specific indices is given below − lreplace listname firstindex lastindex value1 value2..valuen Example for replacing list items at specific indices is given below. Live Demo #!/usr/bin/tclsh set var {orange blue red green} set var [lreplace $var 2 3 black white] puts $var When the above code is executed, it produces the following result − orange blue black white Set Item at Index The syntax for setting list item at specific index is given below − lset listname index value Example for setting list item at specific index is given below − Live Demo #!/usr/bin/tclsh set var {orange blue red green} lset var 0 black puts $var When the above code is executed, it produces the following result − black blue red green Transform List to Variables The syntax for copying values to variables is given below − lassign listname variable1 variable2.. variablen Example for transforming list into variables is given below − Live Demo #!/usr/bin/tclsh set var {orange blue red green} lassign $var colour1 colour2 puts $colour1 puts $colour2 When the above code is executed, it produces the following result − orange blue Sorting a List The syntax for sorting a list is given below − lsort listname An example for sorting a list is given below − Live Demo #!/usr/bin/tclsh set var {orange blue red green} set var [lsort $var] puts $var When the above code is executed, it produces the following result − blue green orange red Print Page Previous Next Advertisements ”;
Category: tcl-tk
Tcl – Loops
Tcl – Loops ”; Previous Next There may be a situation, where you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages − Tcl language provides the following types of loops to handle looping requirements. Sr.No. Loop Type & Description 1 while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 2 for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. 3 nested loops You can use one or more loop inside any another while, for or do..while loop. Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Tcl supports the following control statements. Sr.No. Control Statement & Description 1 break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. 2 continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. The Infinite Loop A loop becomes infinite loop if a condition never becomes false. The while loop is traditionally used for this purpose. You can make an endless loop by leaving the conditional expression as 1. while {1} { puts “This loop will run forever.” } When the conditional expression is absent, it is assumed to be true. Tcl programmers more commonly use the while {1} construct to signify an infinite loop. NOTE − You can terminate an infinite loop by pressing Ctrl + C keys. Print Page Previous Next Advertisements ”;
Tcl – Dictionary
Tcl – Dictionary ”; Previous Next A dictionary is an arrangement for mapping values to keys. The syntax for the conventional dictionary is shown below − dict set dictname key value # or dict create dictname key1 value1 key2 value2 .. keyn valuen Some examples for creating a dictionary are shown below − Live Demo #!/usr/bin/tclsh dict set colours colour1 red puts $colours dict set colours colour2 green puts $colours set colours [dict create colour1 “black” colour2 “white”] puts $colours When the above code is executed, it produces the following result − colour1 red colour1 red colour2 green colour1 black colour2 white Size of Dict The syntax for getting size of dict is shown below − [dict size dictname] An example for printing the size is shown below − Live Demo #!/usr/bin/tclsh set colours [dict create colour1 “black” colour2 “white”] puts [dict size $colours] When the above code is executed, it produces the following result − 2 Dictionary Iteration A simple dictionary iteration for printing keys and valued of the dictionary is shown below − Live Demo #!/usr/bin/tclsh set colours [dict create colour1 “black” colour2 “white”] foreach item [dict keys $colours] { set value [dict get $colours $item] puts $value } When the above code is executed, it produces the following result − black white Value for Key in Dict The syntax for retrieving value for key in dict is shown below − [dict get $dictname $keyname] An example for retrieving value for key is given below − Live Demo #!/usr/bin/tclsh set colours [dict create colour1 “black” colour2 “white”] set value [dict get $colours colour1] puts $value When the above code is executed, it produces the following result − black All Keys in Dict The syntax for retrieving all keys in dict is shown below − [dict keys $dictname] An example for printing all keys is shown below − Live Demo #!/usr/bin/tclsh set colours [dict create colour1 “black” colour2 “white”] set keys [dict keys $colours] puts $keys When the above code is executed, it produces the following result − colour1 colour2 All Values in Dict The syntax for retrieving all values in dict is shown below − [dict values $dictname] An example for printing all values is shown below − Live Demo #!/usr/bin/tclsh set colours [dict create colour1 “black” colour2 “white”] set values [dict values $colours] puts $values When the above code is executed, it produces the following result − black white Key Exists in Dict The syntax for checking if a key exists in dict is shown below − [dict exists $dictname $key] An example for checking if a key exists in dict is shown below − Live Demo #!/usr/bin/tclsh set colours [dict create colour1 “black” colour2 “white”] set result [dict exists $colours colour1] puts $result When the above code is executed, it produces the following result − 1 Print Page Previous Next Advertisements ”;
Tk – Mega Widgets
Tk – Mega Widgets ”; Previous Next Mega widgets include many complex widgets which is often required in some large scale Tk applications. The list of available mega widgets are as shown below − Sr.No. Widget & Description 1 Dialog Widget for displaying dialog boxes. 2 Spinbox Widget that allows users to choose numbers. 3 Combobox Widget that combines an entry with a list of choices available to the use. 4 Notebook Tabbed widget that helps to switch between one of several pages, using an index tab. 5 Progressbar Widget to provide visual feedback to the progress of a long operation like file upload. 6 Treeview Widget to display and allow browsing through a hierarchy of items more in form of tree. 7 Scrollbar Scrolling widgets without a text or canvas widgets. 8 Scale Scale widget to choose a numeric value through sliders. A simple Tk example is shown below using some mega widgets. #!/usr/bin/wish ttk::treeview .tree -columns “Creator Year” -displaycolumns “Year Creator” .tree heading Creator -text “Creator” -anchor center .tree heading Year -text “Year” -anchor center pack .tree .tree insert {} end -id Languages -text “Languages” .tree insert Languages end -text C -values [list “Dennis Ritchie” “1990”] proc scaleMe {mywidget scaleValue} { $mywidget configure -length $scaleValue } pack [scale .s2 -from 100.0 -to 200.0 -length 100 -background yellow -borderwidth 5 -font{Helvetica -18 bold} -foreground red -width 40 -relief ridge -orien horizontal -variable a -command “scaleMe .s2″ ] pack [ttk::progressbar .p1 -orient horizontal -length 200 -mode indeterminate -value 90] pack [ttk::progressbar .p2 -orient horizontal -length 200 -mode determinate -variable a -maximum 75 -value 20] When we run the above program, we will get the following output − Print Page Previous Next Advertisements ”;
Tcl – Procedures
Tcl – Procedures ”; Previous Next Procedures are nothing but code blocks with series of commands that provide a specific reusable functionality. It is used to avoid same code being repeated in multiple locations. Procedures are equivalent to the functions used in many programming languages and are made available in Tcl with the help of proc command. The syntax of creating a simple procedure is shown below − proc procedureName {arguments} { body } A simple example for procedure is given below − Live Demo #!/usr/bin/tclsh proc helloWorld {} { puts “Hello, World!” } helloWorld When the above code is executed, it produces the following result − Hello, World! Procedures with Multiple Arguments An example for procedure with arguments is shown below − Live Demo #!/usr/bin/tclsh proc add {a b} { return [expr $a+$b] } puts [add 10 30] When the above code is executed, it produces the following result − 40 Procedures with Variable Arguments An example for procedure with arguments is shown below − Live Demo #!/usr/bin/tclsh proc avg {numbers} { set sum 0 foreach number $numbers { set sum [expr $sum + $number] } set average [expr $sum/[llength $numbers]] return $average } puts [avg {70 80 50 60}] puts [avg {70 80 50 }] When the above code is executed, it produces the following result − 65 66 Procedures with Default Arguments Default arguments are used to provide default values that can be used if no value is provided. An example for procedure with default arguments, which is sometimes referred as implicit arguments is shown below − Live Demo #!/usr/bin/tclsh proc add {a {b 100} } { return [expr $a+$b] } puts [add 10 30] puts [add 10] When the above code is executed, it produces the following result − 40 110 Recursive Procedures An example for recursive procedures is shown below − Live Demo #!/usr/bin/tclsh proc factorial {number} { if {$number <= 1} { return 1 } return [expr $number * [factorial [expr $number – 1]]] } puts [factorial 3] puts [factorial 5] When the above code is executed, it produces the following result − 6 120 Print Page Previous Next Advertisements ”;
Tcl – Environment Setup
Tcl – Environment Setup ”; Previous Next 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 of a text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX. The files you create with your text editor are called source files and contain program source code. The source files for Tcl programs are named with the extension “.tcl”. Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, build it, and finally execute it. 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. Let”s have a helloWorld.tcl file as follows. We will use this as a first program, we run on a platform you choose. #!/usr/bin/tclsh puts “Hello World!” Installation on Windows Download the latest version for windows installer from the list of Active Tcl binaries available. The active Tcl community edition is free for personal use. Run the downloaded executable to install the Tcl, which can be done by following the on screen instructions. Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using ”cd” command and then execute the program using the following steps C:Tcl> tclsh helloWorld.tcl We can see the following output. C:Tcl> helloWorld C:Tcl is the folder, I am using to save my samples. You can change it to the folder in which you have saved Tcl programs. Installation on Linux Most of the Linux operating systems come with Tcl inbuilt and you can get started right away in those systems. In case, it”s not available, you can use the following command to download and install Tcl-Tk. $ yum install tcl tk Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using ”cd” command and then execute the program using the following steps − $ tclsh helloWorld.tcl We can see the following output − $ hello world Installation on Debian based Systems In case, it”s not available in your OS, you can use the following command to download and install Tcl-Tk − $ sudo apt-get install tcl tk Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using ”cd” command and then execute the program using the following steps − $ tclsh helloWorld.tcl We can see the following output − $ hello world Installation on Mac OS X Download the latest version for Mac OS X package from the list of Active Tcl binaries available. The active Tcl community edition is free for personal use. Run the downloaded executable to install the Active Tcl, which can be done by following the on screen instructions. Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using ”cd” and then execute the program using the following steps − $ tclsh helloWorld.tcl We can see the following output − $ hello world Installation from Source Files You can use the option of installing from source files when a binary package is not available. It is generally preferred to use Tcl binaries for Windows and Mac OS X, so only compilation of sources on unix based system is shown below. Download the source files. Now, use the following commands to extract, compile, and build after switching to the downloaded folder. $ tar zxf tcl8.6.1-src.tar.gz $ cd tcl8.6.1 $ cd unix $ ./configure —prefix=/opt —enable-gcc $ make $ sudo make install Note − Make sure, you change the file name to the version you downloaded on commands 1 and 2 given above. Print Page Previous Next Advertisements ”;
Tk – Environment
Tk – Environment ”; Previous Next Generally, all Mac and Linux mac come with Tk pre-installed. In case, it”s not available or you need the latest version, then you may need to install it. Windows don”t come with Tcl/Tk and you may need to use its specific binary to install it. The Tk Interpreter It is just a small program that enables you to type Tk 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. Let”s have a helloWorld.tcl file as follows. We will use this as first program, we run on the platform you choose. #!/usr/bin/wish grid [ttk::button .mybutton -text “Hello World”] The following section explains only how to install Tcl/Tk on each of the available platforms. Installation on Windows Download the latest version for windows installer from the list of Active Tcl/Tk binaries available. Active Tcl/Tk community edition is free for personal use. Run the downloaded executable to install the Tcl and Tk, which can be done by following the on screen instructions. Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using cd and then using the following step − C:Tcl> wish helloWorld.tcl Press enter and we will see an output as shown below − Installation on Linux Most Linux operating systems comes with Tk inbuilt and you can get started right away in those systems. In case, it”s not available, you can use the following command to download and install Tcl-Tk. $ yum install tcl tk Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using cd command and then using the following step − $ wish helloWorld.tcl Press enter and we will see an output similar to the following − Installation on Debian Based Systems In case, it”s not available prebuilt in your OS, you can use the following command to download and install Tcl-Tk − $ sudo apt-get install tcl tk Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using cd command and then using the following steps − $ wish helloWorld.tcl Press enter and we will see an output similar to the following − Installation on Mac OS X Download the latest version for Mac OS X package from the list of Active Tcl/Tk binaries available. Active Tcl community edition is free for personal use. Run the downloaded executable to install the Active Tcl, which can be done by following the on screen instructions. Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using cd command and then using the following step − $ wish helloWorld.tcl Press enter and we will see an output as shown below − Installation from Source Files You can use the option of installing from source files when a binary package is not available. It is generally preferred to use Tk binaries for Windows and Mac OS X, so only compilation of sources on unix based system is shown below − Download the source files. Now, use the following commands to extract, compile and build after switching to the downloaded folder. $ tar zxf tk8.6.1-src.tar.gz $ cd tcl8.6.1 $ cd unix $ ./configure —with-tcl=../../tcl8.6.1/unix —prefix=/opt —enable-gcc $ make $ sudo make install Note − Make sure, you change the file name to the version you downloaded on commands 1 and 2 in the above. Print Page Previous Next Advertisements ”;
Tcl – Packages
Tcl – Packages ”; Previous Next Packages are used for creating reusable units of code. A package consists of a collection of files that provide specific functionality. This collection of files is identified by a package name and can have multiple versions of same files. The package can be a collection of Tcl scripts, binary library, or a combination of both. Package uses the concept of namespace to avoid collision of variable names and procedure names. Check out more in our next ”namespace” tutorial. Creating Package A package can be created with the help of minimum two files. One file contains the package code. Other file contains the index package file for declaring your package. The list of steps for creating and using package is given below. STEP 1 : Creating Code Create code for package inside a folder say HelloWorld. Let the file be named HelloWorld.tcl with the code as shown below − # /Users/rajkumar/Desktop/helloworld/HelloWorld.tcl # Create the namespace namespace eval ::HelloWorld { # Export MyProcedure namespace export MyProcedure # My Variables set version 1.0 set MyDescription “HelloWorld” # Variable for the path of the script variable home [file join [pwd] [file dirname [info script]]] } # Definition of the procedure MyProcedure proc ::HelloWorld::MyProcedure {} { puts $HelloWorld::MyDescription } package provide HelloWorld $HelloWorld::version package require Tcl 8.0 STEP 2 : Creating Package Index Open tclsh. Switch to HelloWorld directory and use the pkg_mkIndex command to create the index file as shown below − % cd /Users/rajkumar/Desktop/helloworld % pkg_mkIndex . *.tcl STEP 3 : Adding Directory to Autopath Use the lappend command to add the package to the global list as shown below − % lappend auto_path “/Users/rajkumar/Desktop/helloworld” STEP 4 : Adding Package Next add package to program using package require statement as shown below − % package require HelloWorld 1.0 STEP 5 : Invoking Procedure Now, everything being setup, we can invoke our procedure as shown below − % puts [HelloWorld::MyProcedure] You will get the following result − HelloWorld First two steps create the package. Once package is created, you can use it in any Tcl file by adding the last three statements as shown below − lappend auto_path “/Users/rajkumar/Desktop/helloworld” package require HelloWorld 1.0 puts [HelloWorld::MyProcedure] You will get the following result − HelloWorld Print Page Previous Next Advertisements ”;
Tcl – Namespaces
Tcl – Namespaces ”; Previous Next Namespace is a container for set of identifiers that is used to group variables and procedures. Namespaces are available from Tcl version 8.0. Before the introduction of the namespaces, there was single global scope. Now with namespaces, we have additional partitions of global scope. Creating Namespace Namespaces are created using the namespace command. A simple example for creating namespace is shown below − Live Demo #!/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 When the above code is executed, it produces the following result − 33 In the above program, you can see there is a namespace with a variable myResult and a procedure Add. This makes it possible to create variables and procedures with the same names under different namespaces. Nested Namespaces Tcl allows nesting of namespaces. A simple example for nesting namespaces is given below − Live Demo #!/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 When the above code is executed, it produces the following result − test1 test2 Importing and Exporting Namespace You can see in the previous namespace examples, we use a lot of scope resolution operator and it”s more complex to use. We can avoid this by importing and exporting namespaces. An example is given below − Live Demo #!/usr/bin/tclsh namespace eval MyMath { # Create a variable inside the namespace variable myResult namespace export Add } # Create procedures inside the namespace proc MyMath::Add {a b } { return [expr $a + $b] } namespace import MyMath::* puts [Add 10 30] When the above code is executed, it produces the following result − 40 Forget Namespace You can remove an imported namespace by using forget subcommand. A simple example is shown below − Live Demo #!/usr/bin/tclsh namespace eval MyMath { # Create a variable inside the namespace variable myResult namespace export Add } # Create procedures inside the namespace proc MyMath::Add {a b } { return [expr $a + $b] } namespace import MyMath::* puts [Add 10 30] namespace forget MyMath::* When the above code is executed, it produces the following result − 40 Print Page Previous Next Advertisements ”;
Tcl – Decisions
Tcl – Decisions ”; Previous Next Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general form of a typical decision making structure found in most of the programming languages − Tcl language uses the expr command internally and hence it’s not required for us to use expr statement explicitly. Tcl language provides following types of decision making statements − Sr.No. Statement & Description 1 if statement An ”if” statement consists of a Boolean expression followed by one or more statements. 2 if…else statement An ”if” statement can be followed by an optional ”else” statement, which executes when the Boolean expression is false. 3 nested if statements You can use one ”if” or ”else if” statement inside another ”if” or ”else if” statement(s). 4 switch statement A switch statement allows a variable to be tested for equality against a list of values. 5 nested switch statements You can use one switch statement inside another switch statement(s). The ? : Operator We have covered conditional operator ? : in previous chapter, which can be used to replace if…else statements. It has the following general form − Exp1 ? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ”? expression” is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ”? expression.” If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. An example is shown below. Live Demo #!/usr/bin/tclsh set a 10; set b [expr $a == 1 ? 20: 30] puts “Value of b is $bn” set b [expr $a == 10 ? 20: 30] puts “Value of b is $bn” When you compile and execute the above program, it produces the following result − Value of b is 30 Value of b is 20 Print Page Previous Next Advertisements ”;