如何复制ksh关联数组? [英] How to copy a ksh associative array?

查看:107
本文介绍了如何复制ksh关联数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法复制关联数组?我意识到,使用一个衬纸就可以很容易地复制常规数组:

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.

我了解nameref,但是我想知道是否存在一种复制数组的方式,以使原始数组不受影响.

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.

推荐答案

未测试:

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

已测试:

#!/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[*]}

结果:

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

这篇关于如何复制ksh关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆