0

In ZSH, how do you set the value of an associative array parameter to an array?

e.g.,

% declare -A a=()
% a[first]=(1 2)
zsh: a: attempt to set slice of associative array

And when I try and append the associative array a with the array b it seems to work but silently converts the value of b from an array to a scalar.

% declare -A a=()
% declare -a b=(1 2)
% print ${(t)b}
array
% a+=( [b]=($b) )
% print $a[b]
(1 2)
% print ${#a[b]}
5
% for ((i=1; i<=${#a[b]}; i++)) ; do print -n "${a[b][$i]}" ; done ; echo
(1 2)
%
3
  • 1
    are you sure that's supposed to be possible? I had the impression that ksh was the only shell to support nested data structures. But nested data structures are also a point where you should perhaps consider moving to some other programming language, even though zsh is a bit saner than the other shells :) Commented Oct 11 at 20:01
  • I'm not sure it is. I also absolutely agree that this is a use case that should be solved in a different language such as awk, perl, python, etc. As it is part of zsh's initialization process I didn't want to introduce the overhead of launching a subshell process so I was exploring zsh's array capabilities. I didn't see anything in the manual that said it "can't" be done but I suspect, as you do, that it is beyond the capabilities of the shell. Commented Oct 11 at 20:13
  • While zsh does not have direct support for storing arrays this way, you can get very close using null-separated lists. Try: local -A a=(); in=(1 2); a[fr]=${(pj:\0:)in}; out=("${(0)a[fr]}"); typeset -p out Commented Oct 13 at 5:21

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.