8

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

0

3 Answers 3

29

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}
}
Sign up to request clarification or add additional context in comments.

1 Comment

As a Tcl newbie, this is what I wanted to see. An inline declaration/assignment without weird syntax, like every other language I'm used to.
5

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

3 Comments

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 Note that array set r1 {} doesn't unset existing values.
To unset existing values, we can do unset r1 first, and then array set r1 {}
0

set marks(english) 80

set array_name(key) value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.