列表操作在脚本中使用的频率非常高,基本上每个脚本都会涉及到其中的一些操作,在这里对列表的命令进行实例解析,以加深对列表命令的理解,本文涉及的命令为llength、lindex、lrange、lsearch和lassign。
llength
list
返回一个列表的元素个数,非常简单而又常用的命令。
% llength {This is a tcltk example}
5
返回一个列表的元素个数,非常简单而又常用的命令。
% llength {This is a tcltk example}
5
lindex
list ?index...?
根据索引值,找出列表中索引为index的元素,如果没有index就返回整个列表,如果有多个index就返回列表的子列表的元素,具体示例如下:
返回整个列表:
% lindex {This is a tcltk example}
This is a tcltk example
返回列表中索引为3的元素:
% lindex {This is a tcltk example} 3
tcltk
返回列表中索引为2的元素
% lindex { {This is} a {tcltk example}} 2
tcltk example
返回列表中索引为2的子列表中索引为1
根据索引值,找出列表中索引为index的元素,如果没有index就返回整个列表,如果有多个index就返回列表的子列表的元素,具体示例如下:
返回整个列表:
% lindex {This is a tcltk example}
This is a tcltk example
返回列表中索引为3的元素:
% lindex {This is a tcltk example} 3
tcltk
返回列表中索引为2的元素
% lindex { {This is} a {tcltk example}} 2
tcltk example
返回列表中索引为2的子列表中索引为1