简体   繁体   中英

zsh on MacOS: how to create an associative array (hash table) from the from two column-like scalars?

I have two scalar values in the form of columns:

% echo $key
hom
doc
fam

echo $val
'home'
'Documents'
'Family'

and I want to create associative array from them.

I'm aware about the method of creation the associative array like below:

declare -A my_assoc_arr
my_assoc_arr=(hom home doc Documents fam Family)

But what is the easiest method create an associative array by digesting $key and $val in the form as I have them (scalar, column-like)? Is there any other association syntax, or I need to put my effort into reshuffling $key and $val to the association syntax above?

You probably need a loop, but it's not too messy. You'll just use two read commands to read a line from each string at one time.

typeset -A arr

while IFS= read -u 3 -r k
      IFS= read -u 4 -r v
do
    arr[$k]=$v
done 3<<< $key 4<<< $val

The first read reads from file descriptor 3 (which is redirected from a here string created from $key , the second from file descriptor 4 (likewise redirected from $val ).

$ typeset -p arr
typeset -A arr=( [doc]=Documents [fam]=Family [hom]=home )

(This assumes key and val have the same number of lines. I don't want to go down the rabbit hole of dealing with the alternative, which makes you decide what to do with leftover keys or values.)

In zsh you can also use the 'zip' operator to reshuffle two standard arrays into the associative array syntax you mentioned:

typeset -a keys=("${(f@)key}") vals=("${(f@)val}")
typeset -A arr=("${(@)keys:^vals}")

Some of the pieces:

  • ${f)...} - uses the f parameter expansion flag to split a string on newlines.
  • "${(@)...}" - ensures that empty values and values with spaces are handled (probably not absolutely necessary here).
  • ${...:^...} - zips two arrays together, alternating values from each array. The resulting array will be twice the length of the shortest input array.
  • typeset -A arr=(k1 v1 k2 v2) - creates an associative array from the alternating keys and values.

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