public x,y 定义全局变量,全局有效
private 是在过程中屏蔽public定义的变量,即私有变量,离开过程,就会实效。
local 定义局部变量,作用域只在本过程。
x=30 是赋值语句,将30赋给x
public x,y &&定义全局变量
set proc to kk &&打薯芦颤开过程哗租文件
x=20 &&全局变量赋值
y=50
do a1 &&执行过程a1
?x,y
set proc to
return
*过程序文件kk.prg
proc a1
private x &&定义私有变量,屏蔽调用过程的x
x=30&&x=30
local y &&定数败义局部变量,y为逻辑假
do a2 &&执行a2
?x,y
return
proc a2
x="kkk" &&x赋值,x如果脱离a2过程,x变成全局变量,即x=20
y="mmm" &&y从a1过程出来,变成全局变量,重新赋值“mmm”
return
看着我的解释导顺序,就会明白的
不像c,Tcl的变量在使用前不需要声明。Tcl的变量在它首次被赋值时产生,使用set命令。变量可以用unset命令删除,虽然并不强制需要这样做。
变量的值通过$符号访山友问,也叫变量交换。
Tcl是一个典型的”弱类型定义”语言,这意味者任何类型可以存储在任何变量中。例如,同一个变量可以存储数字,日余嫌期,字符串甚至另一段Tcl script.
Example 1.1:
set foo john
puts Hi my name is $foo
Output: Hi my name is john
Example 1.2:
set month 2
set day 3
set year 97
set date $month:$day:$year
puts $date
Output: 2:3:97
Example 1.3:
set foo puts hi
eval $foo
Output: hi
在这个例子里,变量foo存储了另竖唯手外一段Tcl script.
表达式
包括数学表达式,关系表达式,通常用 expr命令。
Example 2.1:
expr 0 == 1
Output: 0
Example 2.2:
expr 1 == 1
Output: 1
两数比较,true则输出1,false输出0
Example 2.3:
expr 4 + 5
Output: 9
Example 2.4:
expr sin(2)
Output: 0.909297
命令传递
以运算结果替代Tcl命令中的部分
Example 3.1:
puts I am [expr 10 * 2] years old, and my I.Q. is [expr 100 - 25]
Output: I am 20 years old, and my I.Q. is 75
方括号是命令传递的标志
Example 3.2:
set my_height 6.0
puts If I was 2 inches taller, I would be [expr $my_height + (2.0 / 12.0)] feet tall
Output: If I was 2 inches taller, I would be 6.16667 feet tall
命令流控制
Tcl有判断流转(if-elseswitch)和循环控制(whileforforeach)
Example 4.1:
set my_planet earth
if {$my_planet == earth} {
puts I feel right at home.
} elseif {$my_planet == venus} {
puts This is not my home.
} else {
puts I am neither from Earth, nor from Venus.
}
set temp 95
if {$temp <80} {
puts It's a little chilly.
} else {
puts Warm enough for me.
}
Output:
I feel right at home.
Warm enough for me.
Example 4.2:
set num_legs 4
switch $num_legs {
2 {puts It could be a human.}
4 {puts It could be a cow.}
6 {puts It could be an ant.}
8 {puts It could be a spider.}
default {puts It could be anything.}
}
Output:
It could be a cow.
Example 4.3:
for {set i 0} {$i <10} {incr i 1} {
puts In the for loop, and i == $i
}
Output:
In the for loop, and i == 0
In the for loop, and i == 1
In the for loop, and i == 2
In the for loop, and i == 3
In the for loop, and i == 4
In the for loop, and i == 5
In the for loop, and i == 6
In the for loop, and i == 7
In the for loop, and i == 8
In the for loop, and i == 9
Example 4.4:
set i 0
while {$i <10} {
puts In the while loop, and i == $i
incr i 1
}
Output:
In the while loop, and i == 0
In the while loop, and i == 1
In the while loop, and i == 2
In the while loop, and i == 3
In the while loop, and i == 4
In the while loop, and i == 5
In the while loop, and i == 6
In the while loop, and i == 7
In the while loop, and i == 8
In the while loop, and i == 9
Example 4.5:
foreach vowel {a e i o u} {
puts $vowel is a vowel
}
Output:
a is a vowel
e is a vowel
i is a vowel
o is a vowel
u is a vowel
Procedures
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)