Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Copy assiociative arrays



René Neumann wrote:
> Am 21.03.2012 22:46, schrieb Moritz Bunkus:
>> Hey,
>> 
>> what about
>> 
>> $ declare -A foo bar
>> $ foo=(a 42 b 54)
>> $ bar=(${(kv)foo})
>> $ print ${(kv)bar}
>> a 42 b 54
>> 
>>> using this, bar only contains the values of foo (and using ${(kv)foo}
>>> instead still only makes it a string).
>> 
>> Yes, because you didn't put it into parenthesis, bar=${(kv)foo} vs
>> bar=(${(kv)foo})
>
> This makes sense. Thanks for the pointer :)

Almost. If one of the values in the source hash is empty, this will
fail:

[snip]
zsh% typeset -A bar
zsh% typeset -A foo
zsh% foo=( a foo b bar c "" )
zsh% bar=( ${(kv)foo} )
zsh: bad set of key/value pairs for associative array
[snap]

To cover that situation you got two options, which are equivalent:

  % bar=( "${(kv@)foo}" )
  % bar=( "${(kv)foo[@]}" )

Whichever you like better.

Regards, Frank



Messages sorted by: Reverse Date, Date, Thread, Author