2015年(19)
分类: 系统运维
2015-11-10 10:51:48
在上一章中我们提到了列表,在本章中做一个详细一些的介绍。
TCL列表是一个系列的值,使用空格进行分割,很容易让人想到C++和JAVA语言中的数组。在TCL中,通过list命令来将一个系列的值变为一个列表,如
set numberlist [list 1 2 3 4 5 6]
numberlist就是一个简单的列表。
[ppcorn@localhost ppcorn]$ cat numlist.tcl
#!/usr/bin/tclsh
set numberlist [list 1 2 3 4 5 6]
puts $numberlist
[ppcorn@localhost ppcorn]$ ./numlist.tcl
1 2 3 4 5 6
对于列表来说,常用的操作有以下:
命令 |
用法 |
list arg1 arg2 |
根据所有的值构造一个列表 |
lindex list i |
返回list的第i个元素 |
llength list |
返回list的元素个数 |
lrange i j |
返回list中从第i个到第j个的元素 |
lappend list arg1 arg2 |
将元素追加到list的后面 |
linsert list index arg |
将元素追加到list中位于index之前的位置 |
lreplace list i j arg arg |
将list中从i到j的元素替换为args |
lsearch ?mode? list value |
根据mode(-exact –glob或-regexp)返回list中与value匹配的元素索引,如果没有就返回-1 |
lsort ?switches? list |
根据开关选项对list进行排序 |
concat list list |
将多个list连接 |
join list joinstring |
以joinstring为分隔符,将列表中的元素合并在一起 |
split string split chars |
使用split chars中的字符串作为列表元素的分割 |
很容易看出来,对单个列表进行操作的命令,都是以l(list)开头。
就列表而言,应该来说使用机会较多,下面使用程序对上述的命令进行演示。
ppcorn@localhost:~/tcl$ cat listtest.tcl
#!/usr/bin/tclsh
set numberlist [list 1 2 3 4 5 6 7 8 9 0]
# lindex to put the value of No.9, it is 0
puts [lindex $numberlist 9]
# llength to return the length of list, it is 10
puts [llength $numberlist]
# lrange to return to value from No.4 to No.6, it is 5 6 7
puts [lrange $numberlist 4 6]
# lappend to add a var to the end of list
# The value should be 1 2 3 4 5 6 7 8 9 0 a
lappend numberlist a
puts $numberlist
# linsert to insert a var before the postion and return a new list
# it will not change the value of numberlist
# The numberlist1 should be 1 2 3 4 5 b 6 7 8 9 0 a
set numberlist1 [linsert $numberlist 5 b]
puts $numberlist
puts $numberlist1
# lreplace to replace the value from i to j with arg and return a new list
# it will not change the numberlist
# The numberlist2 should be 1 a b c 5 6 7 8 9 0 a
set numberlist2 [lreplace $numberlist 1 3 a b c]
puts $numberlist
puts $numberlist2
# lsearch
# the value should be 8
puts [lsearch $numberlist 9]
# lsort
# the value should be 0 1 2 3 4 5 6 7 8 9 a
puts [lsort $numberlist]
# concat
# The value should be 1 2 3 4 5 6 7 8 9 0 a a b c d
puts [concat $numberlist [list a b c d]]
# join
# the value should be 1:2 3 : 4 5 6
puts [join {1 {2 3} {4 5 6} } : ]
# split
# the value should be ab defg
puts [split abcdefg c]
ppcorn@localhost:~/tcl$ ./listtest.tcl
0
10
5 6 7
1 2 3 4 5 6 7 8 9 0 a
1 2 3 4 5 6 7 8 9 0 a
1 2 3 4 5 b 6 7 8 9 0 a
1 2 3 4 5 6 7 8 9 0 a
1 a b c 5 6 7 8 9 0 a
8
0 1 2 3 4 5 6 7 8 9 a
1 2 3 4 5 6 7 8 9 0 a a b c d
1:2 3:4 5 6
ab defg
如果需要熟练掌握上述的列表功能的话,我想,经过一段时间的运用就可以了。