1. 程式人生 > >tcl/tk參考——變數和過程array

tcl/tk參考——變數和過程array

.

.

名稱

array - 處理陣列變數

語法

array option arrayName ?arg arg ...?

描述

這個命令執行幾種可選項中的一個操作,操作的物件為arrayName,除非以下的命令特殊宣告,否則arrayName必須是存在的陣列變數名稱。option變元決定了要對陣列變數進行什麼樣的操作,具體如下:

如果在一次陣列搜尋當中陣列中還有剩餘的元素就返回1,如果沒有剩餘的元素就返回0searchId指定了被檢查arrayName的搜尋標示符,這個標示符必須是命令array startsearch返回的搜尋標示符。這個命令在陣列有空索引的元素時非常有用,因為array nextelement
的返回值並不能說明搜尋是否完畢。
這個命令終結一次陣列搜尋,searchId指出了需要終結的陣列搜尋標示符,這個標示必須是命令array startsearch返回的搜尋標示符。返回一個空字串。
如果arrayName是一個數組變數就返回1,如果沒有這個變數或者是非陣列變數就返回0
返回一個列表,列表中的元素是成對的,交替的出現索引和對應陣列值,如果不指定pattern,所有陣列的元素都回返回,如果指定了pattern,只有匹配pattern(與string match匹配風格相同)的陣列元素返回。如果arrayName不是一個數組變數的名字或者沒有包含任何元素就返回一個空列表。
返回一個匹配pattern
的陣列元素索引的列表,mode可以是-exact-glob-regexp中的一個,指定了匹配的風格,如果不指定mode,預設為-glob。如果需要了解詳細的匹配風格請參考string matchregexp。如果不指定pattern則返回陣列中所有的索引,如果arrayName不是一個數組變數的名字或者沒有包含任何元素就返回一個空列表。
返回arrayName陣列中的下一個元素索引,如果陣列中所有的元素都搜尋到了就返回空字串,searchId指出了需要終結的陣列搜尋標示,這個標示必須是命令array startsearch返回的搜尋標示。警告:如果陣列中有新增和刪除元素的操作,那麼所有的搜尋都回自動結束,就像是呼叫了array donesearch
,這將會導致array nextelement操作失敗。
設定一個或多個數組元素,list必須是像array get返回值風格的列表,第奇數個列表元素被認為是arrayName的一個元素索引,緊接著的第偶數個列表元素就被當作前一個元素的陣列中的值,如果變數arrayName不存在或者為空,就建立一個空陣列arrayName
返回一個十進位制的字串數值來指出陣列中元素的數量,如果arrayName不是一個數組的名字就返回0
這個命令開始在arrayName陣列中進行一個元素一個元素的搜尋,array nextelement命令返回下一元素的索引,當搜尋完畢,array donesearch命令必須呼叫,返回值是一個搜尋標示符,這個搜尋表示符可以在array nextelementarray donesearch中使用來標示操作的搜尋,通過使用搜索標示符允許對一個數組同時進行不同的搜尋。目前,普遍使用的方式是使用array getarray namesforeach一起使用來遍歷陣列中的每一個元素。具體請參考下面的示例。
返回陣列中元素在雜湊表的分配方式的統計,這個命令包含表格中條目數,buckets數目和buckets的利用情況。
刪除陣列中所有匹配pattern的元素(與string match匹配風格相同),如果arrayName不是一個數組變數或者沒有匹配到任何元素,不會產生錯誤,如果忽略了pattern變元並且arrayName是一個數組名稱,這個命令將刪除整個陣列所有的元素,這個命令總是返回一個空字串。

示例

array set colorcount {
   red   1
   green 5
   blue  4
   white 9
}

foreach {color count} [array get colorcount] {
   puts "Color: $color Count: $count"
}
   Color: blue Count: 4
    Color: white Count: 9
    Color: green Count: 5
    Color: red Count: 1
foreach color [array names colorcount] {
   puts "Color: $color Count: $colorcount($color)"
}
   Color: blue Count: 4
    Color: white Count: 9
    Color: green Count: 5
    Color: red Count: 1

foreach color [lsort [array names colorcount]] {
   puts "Color: $color Count: $colorcount($color)"
}
   Color: blue Count: 4
    Color: green Count: 5
    Color: red Count: 1
    Color: white Count: 9

array statistics colorcount
   4 entries in table, 4 buckets
    number of buckets with 0 entries: 1
    number of buckets with 1 entries: 2
    number of buckets with 2 entries: 1
    number of buckets with 3 entries: 0
    number of buckets with 4 entries: 0
    number of buckets with 5 entries: 0
    number of buckets with 6 entries: 0
    number of buckets with 7 entries: 0
    number of buckets with 8 entries: 0
    number of buckets with 9 entries: 0
    number of buckets with 10 or more entries: 0
    average search distance for entry: 1.2