A Symbolic Gesture

Much of Tcl’s strength as a programming languages lies in the manipulation of strings and lists. Compare the following two methods for printing each element of a list:

set cpu_types [list pentium sparc powerpc m88000 alpha mips hppa]

# "C-like" method of iterative processing
for {set i 0} {$i < [llength $cpu_types]} {incr i} {
    puts [lindex $cpu_types $i]
}

# "The Tcl Way"-using string symbols
foreach cpu $cpu_types {
    puts $cpu
}

The loop coded with for is similar to how a C program might be coded, iterating over the list by the use of an integer index value. The second loop, coded with foreach, is more natural for Tcl. The loop coded with foreach contains over 50% less characters, contributing to greater readability and less code to maintain. In addition, the second loop executes much more quickly.

As a general rule, if you find that your code contains many for commands and integer indexing, check whether you may be able to reimplement your algorithms with lists and foreach.

Get Tcl/Tk in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.