How to initialize an array in Tcl?

Amir Rachum picture Amir Rachum · Jul 28, 2010 · Viewed 30.4k times · Source

What is the proper way to initialize an empty array in Tcl?

I have the following code (simplified):

proc parseFile {filename results_array} {
    upvar $results_array results
    set results(key) $value
}

set r1 {}
parseFile "filename" r1

and I get the error:

Error: can't set "results(key)": variable isn't array

Answer

Bryan Oakley picture Bryan Oakley · Jul 28, 2010

To initialize an array, use "array set". If you want to just create the internal array object without giving it any values you can give it an empty list as an argument. For example:

array set foo {}

If you want to give it values, you can give it a properly quoted list of key/value pairs:

array set foo {
    one {this is element 1}
    two {this is element 2}
}