您的位置:首页 > 其它

tcltk实例详解——列表操作(一)

2008-04-28 10:18 666 查看
列表操作在脚本中使用的频率非常高,基本上每个脚本都会涉及到其中的一些操作,在这里对列表的命令进行实例解析,以加深对列表命令的理解,本文涉及的命令为list、concat、lrepeat、join和split。

list ?arg arg ...?
concat ?arg arg ...?
使用多个arg来组成一个列表,这两个命令使用频度很高,使用也非常简单,所需要注意的地方就是list和concat的区别,以下使用具体的例子来说明两个命令的区别。
% list This is a tcltk example
This is a tcltk example
% concat This is a tcltk example
This is a tcltk example
以上的例子并没有看出两个命令有什么区别,在这种情况下两个命令的结果并没有什么区别,两个命令的区别主要是list把后面的参数都当作列表的一个元素看待,形成的列表为所有的元素组成,而concat把后面的参数当作一个列表来看待,形成的列表为所有列表中的元素组成。如果两个命令后面的参数有列表变量就可以看出区别了:
% list {This is} {a} {tcltk example}
{This is} a {tcltk example}
% concat {This is} {a} {tcltk example}
This is a tcltk example
concat可以形象地说是去掉了一层列表结构,然后再list所有的元素。使用时需要注意两者的却别。

lrepeat number element1 ?element2 element3 ...?
使用重复的元素构建列表,number为重复的次数,element为重复的元素,这个命令就相当于对重复number次的element元素进行了list操作,所以lrepeat 1 arg ... 和list arg ... 执行结果相同。如下例:
% lrepeat 3 This is a tcltk example
This is a tcltk example This is a tcltk example This is a tcltk example
下例与list命令结果相同:
% lrepeat 1 This is a tcltk example
This is a tcltk example

join list ?joinString?
split string ?splitChars?
这两个命令为一对相反的命令,它们操作的过程都为对方的逆过程。join命令把一个列表中的元素使用joinString连接成一个字符串,而split是根据splitChars把一个字符串分割为列表。如果没有后面的可选变元,分割符默认为空白符。如下例:
% join {This is a tcltk example} ?
This?is?a?tcltk?example
% split This?is?a?tcltk?example ?
This is a tcltk example
第二个命令使用第一个命令的结果作为参数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: