实战Tcl和TK程序设计 第一章 TCL基础
时间:2007-06-29 来源:oychw
§0 序言
Tcl(Tool Command Language)包含脚本语言以及该脚本语言的解释器.该解释器可以很容易低地嵌入倒你的应用程序中.
Tcl 的实质是工具之间的相互协作.
为什么要使用TCL?
适合自动化处理
与TCL的C函数库用清晰的接口,并便于使用.Tcl和Tk提供了可移植的虚拟机
扩展性好,最著名的扩展是Tk. 它的优点,开发周期快,用户界面接口良好.
与其他语言比,结构简单,类似C,可以通过编制C过程来增添新的Tcl原语,易学.
其他:Tcl也支持Java和浏览器中运行.
TCL 相关网址:
http://www.beedub.com/book/
http://www.tcl.tk/resource/
http://www.sourceforge.net/projects/tcl
http://www.sourceforge.net/projects/tktoolkit
http://tcl.activestate.com/
http://www.purl.org/NET/Tcl-FAQ/
http://wiki.tcl.tk/
ftp://ftp.tcl.tk/pub/tcl
ftp://src.doc.ic.ac.uk/packages/tcl/
ftp://ftp.luth.se/pub/unix/tcl/
ftp://ftp.sunet.se/pub/lang/tcl
ftp://ftp.cs.columbia.edu/archives/tcl
ftp://ftp.funet.fi/pub/languages/tcl
http://groups.google.com
§1 TCL的基本知识
本章描述TCL脚本语言的基本语法规则。包含了TCL解释器的基本机制:替换和分组。并涉及了以下命令:puts,
format, set, expr, string, while, incr, and proc.
TCL是基于命令的字符串语言,它的基本机制和字符串以及字符串替换有关。
TCL 命令
TCL命令处理器行为的三个基本步骤:
变元分组
对嵌套命令,变量和反斜杠换码序列进行替换
调用命令
Hello world 实例:
[root@Meil89 meil]# tclsh
% puts stdout {hello world!}
hello world!
变量
Puts是命令, 后面的是变元
花括号内的整体是一个变元
变量
% set var 5
5
% set b $var
5
% puts $var
5
%
命令替换
嵌套命令由方括号来界定, 类似shell命令的逆向引号,还可以支持命令的任意嵌套.
% set len [string length foobar]
6
数学表达式
Expr 专门执行运算,TCL 解释器不处理. 运算内容用花括号括起来,效率比较高点
% expr 7.2/4
1.8
设定精度:
expr 1 / 3
=> 0
expr 1 / 3.0
=> 0.333333333333
set tcl_precision 17
=> 17
expr 1 / 3.0
# The trailing 1 is the IEEE rounding digit
=> 0.33333333333333331
反斜杠替换
List可以代替大量的反斜杠
TCL只进行一遍解释, 不过eval不是
使用花括号和双引号进行分组
双引号会进行替换,花括号不会.在晚些时候替换一般使用花括号. 引号经常与format一起使用,puts默认已经有一个换行.
分组在替换之前进行
过程
语法如下:
proc name arglist body
本书中过程名以大写字母开头,变量名以小写开头.
While 和if 后面的花括号一般要和条件在一行,不在一行要添加反斜杠.条件的判断一般要用花括号括起来.以延迟替换.
阶乘的实例:
% proc Factorial {x} {
set i 1; set product 1
while {$i <= $x} {
set product [expr {$product * $i}]
incr i
}
return $product
}
% Factorial 10
3628800
指针变量:
set var {the value of var}
=> the value of var
set name var
=> var
set name
=> var
set $name
=> the value of var
确定变量是否存在
if {![info exists foobar]} {
set foobar 0
} else {
incr foobar
}
注释
开头的#才是注释,其他的不是,这样实现:
# Here are some parameters
set rate 7.0 ;# The interest rate
set months 60 ;# The loan term
#注释中,反斜杠依然有效.,花括号也依然有用,所以注释中要小心这个两个符号
Reference
Backslash Sequences
Table 1-1. Backslash sequences |
|
\a |
Bell. (0x7) |
\b |
Backspace. (0x8) |
\f |
Form feed. (0xc) |
\n |
Newline. (0xa) |
\r |
Carriage return. (0xd) |
\t |
Tab. (0x9) |
\v |
Vertical tab. (0xb) |
\<newline> |
Replace the newline and the leading white space on the next line with a space. |
\\ |
Backslash. ('\') |
\ooo |
Octal specification of character code. 1, 2, or 3 octal digits (0-7). |
\xhh |
Hexadecimal specification of character code. 1 or 2 hex digits. Be careful when using this in a string of characters, because all hexadecimal characters following the \x will be consumed, but only the last 2 will specify the value. |
\uhhhh |
Hexadecimal specification of a 16-bit Unicode character value. 4 hex digits. |
\c |
Replaced with literal c if c is not one of the cases listed above. In particular, \$, \", \{, \}, \], and \[ are used to obtain these characters. |
Arithmetic Operators
Table 1-2. Arithmetic operators from highest to lowest precedence |
|
- ~ ! |
Unary minus, bitwise NOT, logical NOT. |
* / % |
Multiply, divide, remainder. |
+ - |
Add, subtract. |
<< >> |
Left shift, right shift. |
< > <= >= |
Comparison: less, greater, less or equal, greater or equal. |
== != eq ne |
Equal, not equal, string equal (Tcl 8.4), string not equal (Tcl 8.4). |
& |
Bitwise AND. |
^ |
Bitwise XOR. |
| |
Bitwise OR. |
&& |
Logical AND. |
|| |
Logical OR. |
x?y:z |
If x then y else z. |
Built-in Math Functions
Table 1-3. Built-in math functions |
|
acos(x) |
Arccosine of x. |
asin(x) |
Arcsine of x. |
atan(x) |
Arctangent of x. |
atan2(y,x) |
Rectangular (x,y) to polar (r,th). atan2 gives th. |
ceil(x) |
Least integral value greater than or equal to x. |
cos(x) |
Cosine of x. |
cosh(x) |
Hyperbolic cosine of x. |
exp(x) |
Exponential, ex. |
floor(x) |
Greatest integral value less than or equal to x. |
fmod(x,y) |
Floating point remainder of x/y. |
hypot(x,y) |
Returns sqrt(x*x + y*y). r part of polar coordinates. |
log(x) |
Natural log of x. |
log10(x) |
Log base 10 of x. |
pow(x,y) |
x to the y power, xy. |
sin(x) |
Sine of x. |
sinh(x) |
Hyperbolic sine of x. |
sqrt(x) |
Square root of x. |
tan(x) |
Tangent of x. |
tanh(x) |
Hyperbolic tangent of x. |
abs(x) |
Absolute value of x. |
double(x) |
Promote x to floating point. |
int(x) |
Truncate x to an integer. |
round(x) |
Round x to an integer. |
rand() |
Return a random floating point value between 0.0 and 1.0. |
srand(x) |
Set the seed for the random number generator to the integer x. |
wide(x) |
Promote x to a wide (64-bit) integer. (Tcl 8.4) |
Core Tcl Commands
The pages listed in Table 1-4 give the primary references for the command.
Table 1-4. Built-in Tcl commands |
||
Command |
Pg. |
Description |
after |
228 |
Schedule a Tcl command for later execution. |
append |
56 |
Append arguments to a variable's value. No spaces added. |
array |
97 |
Query array state and search through elements. |
binary |
59 |
Convert between strings and binary data. |
break |
83 |
Exit loop prematurely. |
catch |
83 |
Trap errors. |
cd |
122 |
Change working directory. |
clock |
183 |
Get the time and format date strings. |
close |
121 |
Close an open I/O stream. |
concat |
65 |
Concatenate arguments with spaces between. Splices lists. |
console |
29 |
Control the console used to enter commands interactively. |
continue |
83 |
Continue with next loop iteration. |
error |
85 |
Raise an error. |
eof |
116 |
Check for end of file. |
eval |
130 |
Concatenate arguments and evaluate them as a command. |
exec |
105 |
Fork and execute a UNIX program. |
exit |
124 |
Terminate the process. |
expr |
6 |
Evaluate a math expression. |
fblocked |
233 |
Poll an I/O channel to see if data is ready. |
fconfigure |
231 |
Set and query I/O channel properties. |
fcopy |
250 |
Copy from one I/O channel to another. |
file |
108 |
Query the file system. |
fileevent |
229 |
Register callback for event-driven I/O. |
flush |
116 |
Flush output from an I/O stream's internal buffers. |
for |
82 |
Loop construct similar to C for statement. |
foreach |
79 |
Loop construct over a list, or lists, of values. |
format |
56 |
Format a string similar to C sprintf. |
gets |
119 |
Read a line of input from an I/O stream. |
glob |
122 |
Expand a pattern to matching file names. |
global |
90 |
Declare global variables. |
history |
196 |
Use command-line history. |
if |
76 |
Test a condition. Allows else and elseif clauses. |
incr |
12 |
Increment a variable by an integer amount. |
info |
186 |
Query the state of the Tcl interpreter. |
interp |
292 |
Create additional Tcl interpreters. |
join |
72 |
Concatenate list elements with a given separator string. |
lappend |
66 |
Add elements to the end of a list. |
lindex |
68 |
Fetch an element of a list. |
linsert |
68 |
Insert elements into a list. |
list |
65 |
Create a list out of the arguments. |
llength |
68 |
Return the number of elements in a list. |
load |
697 |
Load shared libraries that define Tcl commands. |
lrange |
68 |
Return a range of list elements. |
lreplace |
68 |
Replace elements of a list. |
lsearch |
69 |
Search for an element of a list that matches a pattern. |
lset |
62 |
Set an element in a list. (Tcl 8.4) |
lsort |
70 |
Sort a list. |
namespace |
213 |
Create and manipulate namespaces. |
open |
116 |
Open a file or process pipeline for I/O. |
package |
175 |
Provide or require code packages. |
pid |
124 |
Return the process ID. |
proc |
87 |
Define a Tcl procedure. |
puts |
119 |
Output a string to an I/O stream. |
pwd |
122 |
Return the current working directory. |
read |
120 |
Read blocks of characters from an I/O stream. |
regexp |
158 |
Match regular expressions. |
regsub |
162 |
Substitute based on regular expressions. |
rename |
88 |
Change the name of a Tcl command. |
return |
86 |
Return a value from a procedure. |
scan |
58 |
Parse a string according to a format specification. |
seek |
121 |
Set the seek offset of an I/O stream. |
set |
5 |
Assign a value to a variable. |
socket |
239 |
Open a TCP/IP network connection. |
source |
26 |
Evaluate the Tcl commands in a file. |
split |
71 |
Chop a string up into list elements. |
string |
49 |
Operate on strings. |
subst |
140 |
Substitute embedded commands and variable references. |
switch |
77 |
Test several conditions. |
tell |
121 |
Return the current seek offset of an I/O stream. |
time |
202 |
Measure the execution time of a command. |
trace |
193 |
Monitor variable assignments. |
unknown |
178 |
Handle unknown commands. |
unset |
13 |
Delete variables. |
uplevel |
138 |
Execute a command in a different scope. |
upvar |
91 |
Reference a variable in a different scope. |
variable |
207 |
Declare namespace variables. |
vwait |
230 |
Wait for a variable to be modified. |
while |
79 |
Loop until a boolean expression is false. |