Does Tcl Have Do Loop?

When I first started scripting with Tcl, I wish it has C’s do loop, that is, do … until and do … while. After asking my co-workers, the conclusion was Tcl does have do loop. It turns out that Tcl indeed does not have do loop, but it does provide package which does: the control package.

Below is a sample script which uses the control package and demonstrates the two different do loops

#!/usr/bin/env tclsh

# Demonstrates do loop

package require control

# Example 1: Prints 1 to 10 using do..until
set i 0
control::do {
    incr i
    puts -nonewline "$i "
} until {$i >= 10}
puts ""

# Example 2: Same output using do..while
set i 0
control::do {
    incr i
    puts -nonewline "$i "
} while {$i < 10}
puts ""

The first step is to include the control package (line 5). After that, you can use the do loop as you would in C.


6 thoughts on “Does Tcl Have Do Loop?

  1. Pingback: A simpler Tcl for Loop « Hai’s Blog

  2. Vishal

    Thank you so much. Yes I couldn’t find a do-while loop in TCL anywhere until I stumbled upon your article. Thanks it saved my day!

  3. Vishal

    Hello Hai,
    I just added this package in my tcl script but when I try to load the scipt it says “can’t find package control”. I’m using HP nonstop OS, can you help me out if anything I’m missing here?

  4. Hai Post author

    @Vishal: the control package is part of tcllib. On the Mac, ActiveTcl and most Linux implementations, the tcllib software package is installed automatically. I don’t know how to install this package on HP. I am sorry about that.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s