Tuesday, April 4, 2017

Tcl-Tk - Quick Guide

Tcl - Overview

Tcl is shortened form of Tool Command Language. John Ousterhout of the University of California, Berkeley, designed it. It is a combination of a scripting language and its own interpreter that gets embedded to the application, we develop with it.

Tcl was developed initially for Unix. It was then ported to Windows, DOS, OS/2, and Mac OSX. Tcl is much similar to other unix shell languages like Bourne Shell (Sh), the C Shell (csh), the Korn Shell (sh), and Perl.
It aims at providing ability for programs to interact with other programs and also for acting as an embeddable interpreter. Even though, the original aim was to enable programs to interact, you can find full-fledged applications written in Tcl/Tk.

Features of Tcl

The features of Tcl are as follows −
  • Reduced development time.
  • Powerful and simple user interface kit with integration of TK.
  • Write once, run anywhere. It runs on Windows, Mac OS X, and almost on every Unix platform.
  • Quite easy to get started for experienced programmers; since, the language is so simple that they can learn Tcl in a few hours or days.
  • You can easily extend existing applications with Tcl. Also, it is possible to include Tcl in C, C++, or Java to Tcl or vice versa.
  • Have a powerful set of networking functions.
  • Finally, it's an open source, free, and can be used for commercial applications without any limit.

Applications

Tcl is a general-purpose language and you can find Tcl everywhere. It includes,
  • Scalable websites that are often backed by databases.
  • High performance web servers build with TclHttpd.
  • Tcl with CGI based websites.
  • Desktop GUI applications.
  • Embedded applications.

Tcl - Environment Setup

Try it Option Online

We have set up the Tcl/Tk Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online.
Try the following example using our online compiler available at CodingGround
puts "Hello World!"
 
For most of the Tcl examples given in this tutorial, you will find Try it option, so just make use of it and enjoy your learning. For Tk examples, you will need to have a console to see graphical results; so, we recommend to have your own Tk setup.

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.

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.
S.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 setting this to 1 and 0 respectively.
8 tcl_library
Used for setting the location of standard Tcl libraries.
9 tcl_pkgPath
Provides the list of directories where packages are generally installed.
10 tcl_patchLevel
Refers to the current patch level of the Tcl interpreter.
11 tcl_platform
Used for representing the array of elements with objects including byteOrder, machine, osVersion, platform, and os.
12 tcl_precision
Refers to the precision i.e. number of digits to retain when converting to floating-point numbers to strings. The default value is 12.
13 tcl_prompt1
Refers to the primary prompt.
14 tcl_prompt2
Refers to the secondary prompt with invalid commands.
15 tcl_rcFileName
Provides the user specific startup file.
16 tcl_traceCompile
Used for controlling the tracing of bytecode compilation. Use 0 for no output, 1 for summary, and 2 for detailed.
17 tcl_traceExec
Used for controlling the tracing of bytecode execution. Use 0 for no output, 1 for summary, and 2 for detailed.
18 tcl_version
Returns the current version of the Tcl interpreter.
The above special variables have their special meanings for the Tcl interpreter.

Examples for using Tcl special variables

Let's see some examples for special variables.

Tcl version

#!/usr/bin/tclsh

puts $tcl_version
When you run the program, you will get a similar output as shown below −
8.6

Tcl Environment Path

#!/usr/bin/tclsh

puts $env(PATH)
When you run the program, you will get a similar output as shown below −
/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/

Tcl Package Path

#!/usr/bin/tclsh

puts $tcl_pkgPath
When you run the program, you will get a similar output as shown below −
/usr/lib64/tcl8.6 /usr/share/tcl8.6 /usr/lib64/tk8.6 /usr/share/tk8.6

Tcl Library

#!/usr/bin/tclsh

puts $tcl_library
When you run the program, you will get a similar output as shown below −
/usr/share/tcl8.6

Tcl Patch Level

#!/usr/bin/tclsh

puts $tcl_patchLevel
When you run the program, you will get a similar output as shown below −
8.6.3

Tcl Precision

#!/usr/bin/tclsh

puts $tcl_precision
When you run the program, you will get a similar output as shown below −
0

Tcl Startup File

#!/usr/bin/tclsh

puts $tcl_rcFileName
When you run the program, you will get a similar output as shown below −
~/.tclshrc

Tcl - Basic Syntax

Tcl is quite simple to learn and let's start creating our first Tcl program!

First Tcl Program

Let us write a simple Tcl program. All Tcl files will have an extension, i.e., .tcl. So, put the following source code in a test.tcl file.
#!/usr/bin/tclsh

puts "Hello, World!" 
Assuming, Tcl environment is setup correctly; let's run the program after switching to file's directory and then execute the program using −
$ tclsh test.tcl
We will get the following output −
Hello, World!
Let us now see the basic structure of Tcl program, so that it will be easy for you to understand basic building blocks of the Tcl language. In Tcl, we use new line or semicolon to terminate the previous line of code. But semicolon is not necessary, if you are using newline for each command.

Comments

Comments are like helping text in your Tcl program and the interpreter ignores them. Comments can be written using a hash_(#) sign in the beginning.
#!/usr/bin/tclsh

# my first program in Tcl
puts "Hello World!" 
Multiline or block comment is written using 'if' with condition '0'. An example is shown below.
#!/usr/bin/tclsh

if 0 {
   my first program in Tcl program
   Its very simple
}
puts "Hello World!" 
Inline comments use ;#. An example is given below.
#!/usr/bin/tclsh

puts "Hello World!" ;# my first print in Tcl program

Identifiers

A Tcl identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, dollars ($) , and digits (0 to 9).
Tcl does not allow punctuation characters such as @, and % within identifiers. Tcl is a case sensitive_ language. Thus Manpower and manpower are two different identifiers in Tcl. Here are some of the examples of acceptable identifiers −
mohd       zara    abc   move_name  a_123
myname50   _temp   j     a23b9      retVal

Reserved Words

The following list shows a few of the reserved words in Tcl. These reserved words may not be used as constant or variable or any other identifier names.
after append array auto_execok
auto_import auto_load auto_load_index auto_qualify
binary Bgerror break catch
cd Clock close concat
continue Dde default else
elseif Encoding eof error
eval Exec exit expr
fblocked Fconfigure fcopy file
fileevent Flush for foreach
format Gets glob global
history If info interp
join Lappend lindex linsert
list Llength load lrange
lreplace Lsearch lsort namespace
open Package pid pkg_mkIndex
proc Puts pwd read
regexp Regsub rename resource
return Scan seek set
socket Source split string
subst Switch tclLog tell
time Trace unknown unset
update Uplevel upvar variable
vwait While

No comments:

Post a Comment