Controlling Loops - 2022.1 English

Vivado Design Suite User Guide: Using Tcl Scripting (UG894)

Document ID
Release Date
2022.1 English

Tcl has few built-in commands such as for, foreach and while that are used to loop or iterate through a section of code.

Their syntax is:

for <start testCondition next body>
foreach <varname list body>
while <testCondition body>

With all the above commands, the entire Tcl script body is executed at each iteration. However, Tcl provides two commands to change the control flow of the loop: break and continue.

The break statement is used to abort the looping command. The continue statement is used to jump to the next iteration of the loop.

Note: When running inside a proc, the loop can also be aborted using the return command. In this case, not only the loop is aborted but the control goes back to the caller of the proc.

For example, let us suppose that we have a file that contains a list of cell names with the format of one instance name per line. The sample code below reads this file and build a Tcl list that only includes the cell names that currently exist in the design. The code reuses the procedure get_file_content that was introduced earlier. If too many cell names are not found inside the current design then the code stops processing the content of the file:

set valid_cell_names [list]
set error 0
set max_errors 1000
foreach line [split [get_file_content ./all_cell_names.lst] \n] {
  if {[get_cells $line] == {}} {
    # cell name not found
    puts " Error - cell $line not found "
    incr error
    if {$error > $max_errors} {
      puts " Too many errors occured. Cannot continue "
    } else {
      # Go to next cell name
  lappend valid_cell_names $line
puts " [llength $valid_cell_names] valid cells have been found "