标签:
Tcl语言
变量和变量赋值
set a "Hello World!" #将字符串赋值给变量a
puts "NS2 say $a" #输出字符串的内容,其中$a表示变量a的内容
输出:NS2 say Hello World!
表达式
Tcl中的表达式用expr这个指令来求解。(expression)
set value [expr 0==1]#判断0==1是否成立
puts $value
输出:0
set value [expr 2+3]
puts $value
输出:5
流程控制
if-else:
set my_planet "earth" if {$my_planet == "earth"} { ... } elseif {$my_planet == "venus"} { ... } else { ... }
switch:
set num_legs 4 switch $num_legs { 2 {puts "It could be a human."} 4 {puts "It could be an cow."} 6 {puts "It could be an ant."} default {puts "It could be anything."} }
for:
for {set i 0} {$i < 5} {incr i 1} { puts "In the for loop, and i == $i" }
while:
set i 0 while($i < 5) { puts "In the while loop, and i == $i" incr i 1 }
foreach:
foreach vowel{a e i o u} { puts "$vowel is a vowel" }
输出:a is a vowel
e is a vowel
i is a vowel
o is a vowel
u is a vowel
过程
Tcl中的【过程】与C语言中的函数类似:proc name params body
name:过程名
params:参数列表
body:过程的主体
例如:
proc sum_proc {a b} { return [expr $a + $b] } set num1 12 set num2 24 set sum [sum_proc $num1 $num2] puts "The sum is $sum"
输出:The sum is 36
有一点值得注意的是,如果在过程外面定义了某个全局变量,而想在过程中使用这个全局变量,需要在过程中声明,声明方式为:global 全局变量名
数组
set myarray(0) "Zero" set myarray(1) "One" set myarray(2) "Two" for {set i 0} {$i < 3} {incr i 1} { puts $myarray($i) }
输出:Zero
One
Two
数组的索引也可以为字符串
set person_info(name) "Fred Smith" set person_info(age) "25" set person_info(occupation) "Plumber" foreach thing {name age occupation} { puts "$thing == $person_info($thing)" }
输出:name == Fred Smith
age == 25
occupation == Plumber
当数组中的索引很多时,没必要在foreach时列出每一个索引,而可以用foreach thing [array names person_info]来代替。
标签:
原文地址:http://www.cnblogs.com/johnsblog/p/4203779.html