简体   繁体   中英

How to copy a ksh associative array?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM