How to copy a ksh associative array?

夙愿已清 提交于 2020-01-07 04:22:27

问题


Is there a way to copy an associative array? I realize that regular arrays can be copied easily with a one liner as such:

set -A NEW_ARRAY $(echo ${OTHER_ARRAY[*]})

but doing so with associative arrays just gives you the values in that manner.

I know about nameref but I'm interested in knowing if there's a way of copying the array such that the original array isn't affected.


回答1:


untested:

typeset -A NEW_ARRAY
for key in "${!OTHER_ARRAY[@]}"; do
    NEW_ARRAY["$key"]="${OTHER_ARRAY[$key]}"
done

tested:

#!/usr/bin/ksh93

OTHER_ARRAY=( [Key1]="Val1" [Key2]="Val2" [Key3]="Val3" )

echo Keys: ${!OTHER_ARRAY[*]}
echo Values: ${OTHER_ARRAY[*]}

typeset -A NEW_ARRAY
for key in "${!OTHER_ARRAY[@]}"; do
    NEW_ARRAY["$key"]="${OTHER_ARRAY[$key]}"
done

echo Keys: ${!NEW_ARRAY[*]}
echo Values: ${NEW_ARRAY[*]}

Result:

/home/exuser>./a
Keys: Key3 Key1 Key2
Values: Val3 Val1 Val2
Keys: Key3 Key1 Key2
Values: Val3 Val1 Val2


来源:https://stackoverflow.com/questions/6651011/how-to-copy-a-ksh-associative-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!