Version 15 of array set

Updated 2012-03-14 08:33:36 by kmukkuciscocom

array set arrayName list

Sets the values of one or more elements in arrayName. List must have a form like that returned by array get, consisting of an even number of elements. Each odd-numbered element in list is treated as an element name within arrayName, and the following element in list is used as a new value for that array element. If the variable arrayName does not already exist and list is empty, arrayName is created with an empty array value.

For example,

 array set val [list a 1 c 6 d 3]
 puts $val(a)
 1
 puts $val(c)
 6
 puts $val(d)
 3

For example how to call using lindex,

 set port {a 1}         
 a 1
 array set val [list [lindex $port 0] [lindex $port 1]]
 puts $val([lindex $port 0])
 1

Note that array set does not remove elements which already exist in the array. For example,

 array set spam {} ;# This does not work

...will not clear out the array spam. To clear an array, can use array unset in version 8.3 and beyond. For example:

 array unset spam

...will remove the array spam if it exists, but will not complain if it does not.

 array unset spam *

...will clear the contents of the array spam, but the array will continue to exist.

This feature makes it easier to work with array variables, but it can come as a surprise to those who expected array set to act like the normal set command (which replaces any existing data in the variable). It might be useful to think of it as array append. - RS: Sometimes array set adds new elements (appending implies some order, which arrays don't so clearly have), sometimes it replaces existing elements. So I still think the name array set is clearer...


See also: