tags:

views:

81

answers:

2

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

+2  A: 

You don't initialize arrays in Tcl, they just appear when you set a member:

proc stash {key array_name value} {
    upvar $array_name a
    set a($key) $value
}

stash one pvr 1
stash two pvr 2
array names pvr

yields:

two one
msw
If you do want to force something to be an array, I often do as it maks the code more readable, you can use 'array set r1 {}' and then r1 is an empty array.
Jackson
@Jackson Note that `array set r1 {}` doesn't unset existing values.
Trey Jackson
+3  A: 

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}
}
Bryan Oakley