Tcl循环语句

for 开始 判断语句 变量自增(自检) 循环体

示例代码:

for {set i 0} {$i<10} {incr i} {

    puts "I is: $i "

}

运行结果

 

While 判断语句 循环体

示例代码:

set x 0

while {$x<5} {

    set x [expr $x+$x+1]

    puts "X: $x"

}

运行结果:

 

foreach 变量名 列表 循环体

队列表中的每一个元素循环执行Tcl脚本块,依次将列表中的值赋给变量名

示例代码:

set total 0

foreach num {1 2 3 4 5} {

    set total [expr $total+$num]

}

puts "The total is: $total"

运行结果:

 

foreach 变量列表1 数据列表1 变量列表2 数据列表2 ... 循环体

示例代码:

foreach {pres date} {{George Washington} {1789-1797}

                     {John Adams} {1797-1801}

                     {Thomas Jefferson} {1801-1809}

                     {James Madison} {1809-1817}

                     {James Monroe} {1817-1825}

} state {Virginia Massachusetts Virginia Virginia Virginia} {

    puts "$pres was from $state and served from $date"

}

foreach当中变量列表和数据列表不匹配,则不匹配部分用空字符串来代替

示例代码:

foreach {pres date} {{George Washington} {1789-1797}

                     {John Adams} {1797-1801}

                     {Thomas Jefferson} {1801-1809}

                     {James Madison} {1809-1817}

                     {James Monroe} {1817-1825}

                     {BillClinton} {1992-2000}

} state {Virginia Massachusetts Virginia Virginia Virginia} {

    puts "$pres was from $state and served from $date"

}

posted @ 2016-04-11 12:15  硫酸亚铜  阅读(1322)  评论(0编辑  收藏  举报