How to initialize an array in Tcl?
Asked Answered
C

3

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

Campaign answered 28/7, 2010 at 4:56 Comment(0)
E
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
Evidence answered 28/7, 2010 at 5:15 Comment(3)
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.Deangelo
@Deangelo Note that array set r1 {} doesn't unset existing values.Much
To unset existing values, we can do unset r1 first, and then array set r1 {}Ashkhabad
O
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}
}
Oxpecker answered 28/7, 2010 at 17:3 Comment(1)
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.Niello
E
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
Evidence answered 28/7, 2010 at 5:15 Comment(3)
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.Deangelo
@Deangelo Note that array set r1 {} doesn't unset existing values.Much
To unset existing values, we can do unset r1 first, and then array set r1 {}Ashkhabad
K
0

set marks(english) 80

set array_name(key) value

Kinematics answered 22/10, 2017 at 8:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.