1.双引号取消其中的单词和命令分隔符的特殊解释,大括号取消其中所有特殊字符的特殊解释
set msg "eggs:\$2.18/dozen\nGasoline:\$1.49"
=> eggs:$2.18/dozen
Gasoline:$1.49
单词不以“开头,”作为普通单词处理
puts this "is" poor "usage
=>this "is" poor "usage
变量替换和命令替换及反斜线替换在“中正常进行
set a 2.1
set msg "a is $a,the square of a is [expr $a*$a]"
=>a is 2.1,the square of a is 4.41
双引号中包含双引号,则也应该用反斜线替换
set name a.out
set msg "could'n open the file \"$name\""
=>could'n open the file "a.out"
2.大括号应用
大括号提供了彻底的引用形式,它会取消所有特殊字符的特殊意义
set msg {eggs:$2.18/dozen\nGasoline:$1.49/gallon}
=>eggs:$2.18/dozen\nGasoline:$1.49/gallon
3.参数展开
file delete [glob *.o]
glob *.o展开后缀为.o的文件,如a.o b.o c.o
a.o b.o c.o作为一个参数传递给file delete,file delete以为找不到名为a.o b.o c.o的文件而失败。要想file delete正常工作,glob的结果必须被正确分割为多个单词。
如果一个单词以字符串{*}开头,之后紧接着为非空白字符,TCL会移除开头的{*},把单词的剩余部分作为含义单词分隔符的语句进行解析和替换。
file delete {*}{glob *.o}
eval file delete {glob *.o}
eval把它的所有单词连接起来,单词之间用空格隔开。
4.注释
#出现在一行的第一个字符为注释,前面可以有空格符
#跟在一个;的后面也被视为注释,其他方式均不为注释
如:
set a 100 #not a comment
不是一个注释
set a 100 ;#not a comment
是一个注释
注意:注释中不要出现{ },否则可能会出现错误
5.append varname value value...
为一个变量追加变量
% set a 2
2
% append a 3 4 5
2345
incr varname increment
increment默认值为1
set varname value
unset varname 删除变量
6.数组
% set earnings(january) 87966
87966
% set earnings(february) 95400
95400
% set earnings(january)
87966
包含空格的数组名
% set cap(new jer) 100
wrong # args: should be
% set cap("new jer") 100
wrong # args: should be
% set cap(new\ jer) 100
100
% set "cap(new jer)" 200
200
7.多维数组
% set m(1,1) 140
140
% set m(1,2) 218
218
% set m(1,3) 84
84
注意m(1,1) 和m(1, 1)
8.查询数组的元素
array size arrayname 返回数组arrayname中元素的个数
array names arrayname 返回数组中元素名
% set c(france) euro
euro
% set "c(great britian)" pound
pound
% set c(jan) yen
yen
% array size c
3
% array names c
{great britian} jan france
% foreach i [array names c] {
if {$i== “jan”} {
puts $c($i)
}
}
yen
array exists 检测数组中摸个特定变量是否存在
array get和array set 可以用于数组和字典之间的相互转换
% set a(head) hat
hat
% set a(hand) glove
glove
% set a(foot) shoe
shoe
% set apparel [array get a]
foot shoe head hat hand glove
% array exists a
1
% array exists apparel
0
% array set b $apparel
% lsort [array names b]
foot hand head
% foreahc i [array names a] {
if { $i=="head"} {
puts $a($i)
}
}
invalid command name "foreahc"
% foreach i [array names a] {
if {$i=="head"} {
puts $a($i)
}
}
hat