UG后处理tcl语言解释

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

exec tclsh ${1+"$@"}

# echo server that can handle multiple

# simultaneous connections.

proc newConnection { sock addr port } {

# client connections will be handled in

# line-buffered, non-blocking mode

fconfigure $sock -blocking no -buffering line

# call handleData when socket is readable

fileevent $sock readable [ list handleData $sock ]

}

proc handleData {

puts $sock [ gets $sock ]

if { [ eof $sock ] } {

close $sock

}

}

# handle all connections to port given

# as argument when server was invoked

# by calling newConnection

set port [ lindex $argv 0 ]

socket -server newConnection $port

# enter the event loop by waiting

# on a dummy variable that is otherwise

# unused.

vwait forever

另外一个TK的例子 (来自 A simple A/D clock) 它使用了定时器时间,3行就显示了一个时钟。

proc every {ms body} {eval $body; after $ms [info level 0]} pack [label .clock -textvar time]

every 1000 {set ::time [clock format [clock sec]

-format %H:%M:%S]} ;# RS

解释:第一行定义了过程every,每隔ms毫秒,就重新执行body代码。第二行创建了标签起内容由time变量决定。第3行中设置定时器,time 变量从当前时间中每秒更新一次。

Tcl被广泛的用做script语言,大多数情况下,Tcl和Tk(“Tool Kit”)库同时使用,Tk是一系列令Tcl易于编写图形用户接口的命令和过程Tcl的一个重要特性是它的扩展性。如果一个程序需要使用某些标准Tcl没有提供的功能,可以使用c语言创造一些新的Tcl命令,并很容易的

融合进去。正是由于Tcl易于扩展,很多人为它编写了扩展包,并在网上共享。

Tcl和其他编程语言例如c不同,它是一种解释语言而非编译语言。Tcl 程序由一系列Tcl命令组成,在运行时由Tcl解释器解释运行。解释运行的一个优点是它可以自己为自己生成Tcl script。

变量和变量交换

不像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-else; switch)和循环控制(while; for; foreach) 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.

相关文档
最新文档