Version 6 of Comparing Tcl with Python

Updated 2005-01-29 14:52:56 by cl

LV wrote: Perhaps the community could contribute tips, references, etc. comparing and contrasting Python and Tcl to provide someone who programs in Python assistance in learning to read/write Tcl?


Sarnold I will try something, while reading the beginning of the Python tutorial.

Using Tcl as a calculator

Firstable, type tclsh at the shell prompt to enter in interactive mode.

 % expr 2+2
 4
 % expr 3*4
 12
 % expr (5*6)/3
 10
 % set a 4
 4
 % expr $a*$a
 64

Every line you read in a Tcl script is a command. Here we have used two commands : expr and set.

expr allows you to compute with integers (and floating-point numbers). It takes the arguments you put after the command name and returns the result of the operations.

As you can see, we have set the variable named 'a' to the value '4'. When refering to the variable content, you have to precede the variable name by a dollar. In some cases (usually the first argument of set), you just need the variable name.

This is IMHO the most confusing thing for someone who comes from imperative programming.

Another example :

 % set a 5
 5
 % set command expr
 expr
 % $command $a+$a
 10

Yes, in Tcl you can call a command named after the value of a variable ! The last line is evaluated by our interpreter as :

 expr 5+5
 ^    ^
 |    |
 |    the value of 'a'
 the value of 'command'

Strings

Forget everything about type conversion, in Tcl everything is a string. Launch tclsh and type :

 % puts work
 work
 % set task sleep
 sleep
 % puts "My task is to $task"
 My task is to sleep
 % puts {My task is to $task}
 My task is to $task
 % puts [expr 2+2]
 4

The puts command is similar to print in Python. It goes to the next line after each call. If you do not want to print a newline, do

 puts -nonewline "Mom"

Lists

 % set a {1 2 3}
 1 2 3
 % lindex $a 0
 1
 % lindex $a 1
 2
 % lindex $a end
 3
 % lrange $a 0 end-1
 1 2
 % lrange $a 1 end
 2 3
 % puts {1 2 $a}
 1 2 $a
 % puts [list 1 2 $a]
 1 2 {1 2 3}

In Python, you can duplicate a list by typing :

 >>> a=[1,2,3]
 >>> a[:0]=a

In Tcl you have to type :

 % set a {1 2 3}
 1 2 3
 % set a [concat $a $a]
 1 2 3 1 2 3

More to come


Does someone want to do more ?

VK I think Sarnold did not understood the point of comparing. We do not want to see exactly how two languages differ, and what namely syntax they have. Rather, comparing of overall structure is more intersting: libraries, repositories, how it scales to large projects, what does it takes to write simple programs... One of interesting points is using Tk from Python, and I know one of standard way of building GUI for Python is using Tk.


Category Language