From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 21222 invoked by alias); 14 Jul 2013 18:05:52 -0000 Mailing-List: contact zsh-users-help@zsh.org; run by ezmlm Precedence: bulk X-No-Archive: yes List-Id: Zsh Users List List-Post: List-Help: X-Seq: 17874 Received: (qmail 3119 invoked from network); 14 Jul 2013 18:05:36 -0000 X-Spam-Checker-Version: SpamAssassin 3.3.2 (2011-06-06) on f.primenet.com.au X-Spam-Level: X-Spam-Status: No, score=-1.9 required=5.0 tests=BAYES_00,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.2 Received-SPF: none (ns1.primenet.com.au: domain at closedmail.com does not designate permitted sender hosts) From: Bart Schaefer Message-id: <130714110527.ZM8869@torch.brasslantern.com> Date: Sun, 14 Jul 2013 11:05:27 -0700 In-reply-to: Comments: In reply to Thorsten Kampe "Re: How to iterate over an array of associative arrays" (Jul 14, 3:36pm) References: X-Mailer: OpenZMail Classic (0.9.2 24April2005) To: Thorsten Kampe , zsh-users@zsh.org Subject: Re: How to iterate over an array of associative arrays MIME-version: 1.0 Content-type: text/plain; charset=us-ascii On Jul 14, 3:36pm, Thorsten Kampe wrote: } } > > AssocArr1=(key value1) } > > AssocArr2=(key value2) } > > } > > array=($AssocArr1 $AssocArr2) } > } > Do you really want these $ here? } } Yes, I really wanted to pass the actual associative arrays, but if I can } pass the names that's fine with me, too. The shell language is text-oriented and can be though of as strictly pass-by-value, so there's no way to create a nested data structure; the values of the array cannot be direct references to other arrays. } > You need to use the (P) flag to access a parameter indirectly. Ksh namerefs, which are partly emulated by zsh's (P) flag, allow you to simulate references but are not true object handles. } Doesn't work for me: } } """ } array=(AssocArr1 AssocArr2) } } for elem in $array } do echo ${${(P)elem}[key]} } done } """ Unfortunately even though ${(P)elem} can access by reference, it can only "return" (expand that reference) by value, and the shell has only two kinds of values: strings or plain arrays. Fortunately, although associative array keys/values are not maintained in any predictable order, they are guaranteed to be returned in a consistent order (as long as no new elements are inserted between accesses) so this can be done: """ declare -A AssocArr AssocArr=(key1 value1 key2 value2 key3 value3) ref=AssocArr print position of key2 is ${${(kP)ref}[(i)key2]} print value for key2 is ${${(P)ref}[${${(@kP)ref}[(i)key2]}]} """ The extra (@) in there is because $arr[key] puts key in double-quoted context, so you have to force ${(P)ref} to remain an array for the subscript operation.