TCL学习之数组(2)

来源:互联网 发布:重庆seo公司 编辑:程序博客网 时间:2024/06/06 04:08

这篇文章接上一篇文章讲述一下关于数组的其他几个函数和知识点。

1.使用foreach 浏览数组内容;

2使用array startsearch,array anymore 和array nextelement 浏览数组内容;

3.数组相关函数列表

序号函数描述1array startsearch arrayName得到数组第一项返回的是ID2array nextelement arrayname searchID得到数组的下一项返回的是ID3array anymore arrayname searchID根据当前的ID判断是否还有内容,返回1为找到返回0表示没有找到4array donsearch arrayname search iD根据ID查找相应项。会破坏相应的状态信息。4.global 和 upvar的使用注意事项

除了global 普通变量函数内外都是用$,其他都是函数外不用$,函数内用$。
示例1:数组元素访问

array set array1 [list {123} {Abigail Aardvark} {234} {Bob Baboon}\{345} {Cathy Coyote}\{456} {Daniel Dog}]foreach id [array names array1] {puts "$array1($id) has ID:$id"}
运行结果


示例2:数组元素访问方法2:

array set array1 [list {123} {Abigail Aardvark} {234} {Bob Baboon} {345} {Cathy Coyote} {456} {Daniel Dog}]proc getrec_format1 {arrayVar searchid} {global $arrayVarupvar $searchid idset record [array nextelement $arrayVar $id];return "the current ID is:$record"}proc getrec_format2 {arrayVar searchid} {global $arrayVarupvar $searchid idset record [array nextelement $arrayVar $id];return $record;}set searchId [array startsearch array1]puts ""set item 0;while {[array anymore array1 $searchId]} {incr item;if {[expr $item%2]} {set format1 [getrec_format1 array1 searchId]puts "item number:$item format1:$format1"} else {set format2 [getrec_format2 array1 searchId]puts "item number:$item format2:$format2"}}
运行结果


示例3:global和upvar普通变量传值的用法

proc tryglobal {glo} {global $gloreturn "the current glo is:$glo"}proc tryglobal1 {glo} {upvar $glo glo1;#注意跟global的区别return "the current glo is:$glo1"}set glo1 "112341234"puts "[tryglobal1 glo1]";#返回glo1,用upvar #就不加$puts "[tryglobal1 glo1]"puts "[tryglobal $glo1]";#返回12341234
运行结果:


示例4:globalhe 

array set arr1 [list {1} {2} {3} {4}]#global传值proc tryarrglobal {arrglo} {global $arrgloreturn "the current glo is:[array names $arrglo]"}puts "[tryarrglobal arr1]"#upvar 传值proc tryarrupvar {arrupvar} {upvar $arrupvar arrupvar1return "the current upvar is:[array names arrupvar1]"}puts "[tryarrupvar arr1]"

这里在做一次总结:对于普通变量,global函数内用$,函数外也用$;对于数组global函数内用$,函数外不用$。对于普通变量,upvar函数内用$,函数外不用$;对于数组,upvar函数内不用$,函数外也不用$.

0 0
原创粉丝点击