Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: How to iterate over an array of associative arrays
- X-seq: zsh-users 17874
- From: Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx>
- To: Thorsten Kampe <thorsten@xxxxxxxxxxxxxxxx>, zsh-users@xxxxxxx
- Subject: Re: How to iterate over an array of associative arrays
- Date: Sun, 14 Jul 2013 11:05:27 -0700
- In-reply-to: <kru9g4$gbm$1@ger.gmane.org>
- List-help: <mailto:zsh-users-help@zsh.org>
- List-id: Zsh Users List <zsh-users.zsh.org>
- List-post: <mailto:zsh-users@zsh.org>
- Mailing-list: contact zsh-users-help@xxxxxxx; run by ezmlm
- References: <kru5ud$fse$1@ger.gmane.org> <CAHYJk3QF3Sk0PUjwr_j0OCeALhsWJM64MsB0aeeGhLkxC7osTg@mail.gmail.com> <kru9g4$gbm$1@ger.gmane.org>
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.
Messages sorted by:
Reverse Date,
Date,
Thread,
Author