gpt4 book ai didi

arrays - 如何使用一系列交替的键和值来定义 Bash 5.1 关联数组?

转载 作者:行者123 更新时间:2023-12-05 01:09:27 27 4
gpt4 key购买 nike

我阅读了release notes of Bash 5.1 :

gg. Associative arrays may be assigned using a list of key-value pairs within a compound assignment. Compound assignments where the words are not of the form [key]=value are assumed to be key-value assignments. A missing or empty key is an error; a missing value is treated as NULL. Assignments may not mix the two forms.

检查 Bash 5.1 Reference Manual → Arrays section我看到了这个新 block (与 Bash 4.4 Reference Manual 相比):

When assigning to an associative array, the words in a compound assignment may be either assignment statements, for which the subscript is required, or a list of words that is interpreted as a sequence of alternating keys and values: name=(key1 value1 key2 value2 … ). These are treated identically to name=( [key1]=value1 [key2]=value2 … ). The first word in the list determines how the remaining words are interpreted; all assignments in a list must be of the same type. When using key/value pairs, the keys may not be missing or empty; a final missing value is treated like the empty string.

This syntax is also accepted by the declare builtin. Individual array elements may be assigned to using the name[subscript]=value syntax introduced above.

所以我做了一个测试:

$ bash --version
GNU bash, version 5.1.0(1)-release (x86_64-apple-darwin18.5.0)
$ declare -a bla
$ bla=( [name]=me )
$ echo "${bla[name]}"
me # it works well

但是,如果我使用新语法,它对我不起作用,它会返回键而不是值:

$ declare -a bla
$ ble=( name me )
$ echo "${ble[name]}"
name # should be "me"

如何正确使用复合赋值作为交替键和值的序列?

最佳答案

这是一个用declare -A定义关联数组的问题(注意“A”的大写字母):

declare -A bla
$ bla=(k1 v1 k2 v2)
$ echo "${bla[k1]}"
v1

如果您尝试混合分配,则会失败,如下所示:

$ bla=([k1]=v1 k2 v2)
bash: bla: k2: must use subscript when assigning associative array
bash: bla: v2: must use subscript when assigning associative array
$ bla=([k1]=v1 [k2]=v2)
$ echo "${bla[k2]}"
v2

关于arrays - 如何使用一系列交替的键和值来定义 Bash 5.1 关联数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65219055/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com