How to assign an associative array to another variable in zsh?

In zsh, is there a way to assign an associative array to another variable? I would like something like this:

typeset -A orig orig=(key1 val1 key2 val2) typeset -A other other=$orig print '$orig: '$orig print '$other: '$other print '$orig[key1]: '$orig[key1] print '$other[key1]: '$other[key1] 

This will print:

 $orig: val1 val2 $other: val1 val2 $orig[key1]: val1 $other[key1]: 

I want to be able to use $other[key1] and get val1 .

I know that I can iterate over the keys and copy them over the elements, but I really want to avoid this. In addition, eval is evil :)

I tried other=($orig) and other options, but this will get my values ​​from orig and create as an associative array like this

 other=(val1 val2) 

So other[key1] returns nothing, and other[val1] returns val2 , which I don't want.

If I understand correctly, what happens in each of mine is that $other receives an array of $orig values ​​without keys. How can I get it to receive both keys and and have the correct connection between them?

I'm not worried about null values, even if that would be a problem, because I'm sure $orig will behave well.

Thanks!

+7
arrays shell associative-array zsh
source share
2 answers

You need to delve into the wonderful world of parameter expansion flags :) Flags k and v can be used together to make the associative array expand to both its keys and values.

 $ typeset -A orig $ orig=(key1 val1 key2 val2) $ print ${(kv)orig} key1 val1 key2 val2 

You can then use the set command to populate your copy with the variable key / values ​​obtained by this extension.

 $ typeset -A other $ set -A other ${(kv)orig} $ print $other[key1] val1 

These and other flags are described in man zshexpn in the "Parameter Extension Flags" section, which is one of my favorite zsh functions.

+10
source share

zsh: bad set of key/value pairs for associative array

Perfect world without escape:

 ➜ typeset -A old new ➜ old=(k1 v1 k2 v2 k3 v3) ➜ typeset old # old=( k1 v1 k2 v2 k3 v3 ) 

... does not exist, and your arrays usually contain empty values:

 ➜ old[k2]= ➜ typeset old # old=( k1 v1 k2 '' k3 v3 ) 

... so you need to use " (quoting), @ (escaping) and f (field separation):

 ➜ typeset new # new=( ) ➜ new=("${(@fkv)old}") ➜ typeset new # new=( k1 v1 k2 '' k3 v3 ) 

For more information on options extension flags, see man zshexpn .

+2
source share

All Articles