array set

array set sets values in an array.

Synopsis

array set arrayName dictionary

Description

Sets the values of one or more variables in arrayName. Each key in dictionary becomes the name of a variable in the array and the corresponding value in the dictionary becomes the value of that variable. If there is no variable named arrayName 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

Example using lindex:

set port {a 1}
array set val [list [lindex $port 0] [lindex $port 1]]
set val([lindex $port 0]) ;# -> 1

Note that array set does not remove variables 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 variables (appending implies some order, which arrays don't so clearly have), sometimes it replaces existing variables. So I still think the name array set is clearer...


RFox 2012-03-14: A better name might have been array merge as that describes exactly what it does.. it merges the list of index/value into the named array creating it if needed. The term merge implies the possible replacement of existing indices and creation of new ones.