Bash
是否有办法在关联数组中为值创建指针?像这样:
declare -A mapp
mapp=( ["key"]="${value}" )
for k in "${!mapp[@]}"; do
pointer="${mapp["${k}"]}" # How do I do this?
done
通常情况下,你不需要 来使用指针,但我很想知道是否有办法制作指针。
在更简单的情况下(例如,对于普通/字符串变量),我会做一个像这样的指针:
pointer=b
read -p "Enter something: " b
eval pointer=\$${pointer}
我如何为关联数组执行此操作?这不起作用(跳过strikethroughed代码):
declare -A mapp
mapp=( ["first"]="${a}" ["second"]="${b}" )
for k in "${!mapp[@]}"; do
v=mapp["${k}"]
read -p "Enter ${k}: " new
eval v=\$${v} # Doesn't work
done
declare -A mapp
mapp=( ["first"]="${a}" ["second"]="${b}" )
for k in "${!mapp[@]}"; do
v=mapp["${k}"]
read -p "Enter ${k}: " k
eval v=\$${v} # Doesn't work
done
这也不起作用(跳过strikethroughed代码):
declare -A mapp
mapp=( ["first"]="${a}" ["second"]="${b}" )
for k in "${!mapp[@]}"; do
v=mapp
read -p "Enter ${k}: " new
eval v=\$${v["${k}"]} # Doesn't work (and has terrible readability)
done
declare -A mapp
mapp=( ["first"]="${a}" ["second"]="${b}" )
for k in "${!mapp[@]}"; do
v=mapp
read -p "Enter ${k}: " k
eval v=\$${v["${k}"]} # Doesn't work (and has terrible readability)
done
答案 0 :(得分:8)
在bash
4.3中,您可以使用nameref:
$ mapp=([key]=value)
$ declare -n x=mapp[key] # NO dollar sign!
$ x=7
$ echo ${mapp[key]}
7
在4.3之前,您需要以不同的方式使用declare
命令来执行间接操作。
$ mapp=([key]=value)
$ x=mapp[key] # NO dollar sign!
$ declare "$x=7"
$ echo ${mapp[key]}
7
答案 1 :(得分:1)
没问题:
$ declare -A ary=([foo]=bar [baz]=qux)
$ key=foo
$ pointer="ary[$key]"
$ echo "$pointer"
ary[foo]
$ echo "${!pointer}"
bar
这个意义上的“指针”是indirect variable