如何在Tcl中初始化数组?

时间:2022-08-22 21:26:15

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

在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

错误:无法设置“结果(键)”:变量不是数组

3 个解决方案

#1


4  

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

您没有在Tcl中初始化数组,它们只是在您设置成员时出现:

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

#2


18  

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

#3


0  

set marks(english) 80

设置标记(英文)80

set array_name(key) value

设置array_name(键)值

#1


4  

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

您没有在Tcl中初始化数组,它们只是在您设置成员时出现:

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

#2


18  

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

#3


0  

set marks(english) 80

设置标记(英文)80

set array_name(key) value

设置array_name(键)值