Tcl Tip #2

Here’s the next in my ongoing list of tcl tips and tricks.

Use foreach to break apart a list in to its components.

In this example I’m working with a description of a temperature range. I’m told the description is a list that starts with the initial temperature, the middle value is the final temperature, and the last value is the step size between them.

set range [list -30 15 5]

If I want to write a script that enumerates all the temperatures in the range. I’m going to need to get each value from the list separately.  Typically, accessing individual elements of the list is done with Tcl’s lindex command.  However, a clever one-liner every once in a while can be really useful.

foreach {initial_value final_value step_size} $range break

The break at the end ensures that if range happened to be a longer list we’d only grab the 1st set of values.

Here’s an example procedure that enumerates all the temperatures.

# get the temperatures in the given range
proc get_temperatures { range } {
    foreach {initial_value final_value step_size} $range break

    set temperatures [list]
    for { set t $initial_value } { $t <= $final_value } { incr t $step_size } {
        lappend temperatures $t
    }

    # make sure the final temperature is included even if the step size was too big to include it 
    if { [lindex $temperatures end] != $final_value } {
        lappend temperatures $final_value
    }
    return $temperatures
}

Tcl’s foreach is a very versatile command. No doubt, we’ll use it again.

 

No comments yet.

Leave a Reply