开发者

How to copy a ksh associative array?

Is there a way to copy an assoc开发者_运维问答iative 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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜