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

Re: indirect array element assignment?

On Sat, Jul 2, 2022 at 3:34 AM Anthony Heading <ajrh@xxxxxxxx> wrote:
> What's the best zsh way of doing an indirect array element assignment?

fruits=("apple" "banana" "carrot")
typeset "${v}[3]"=cherry

There really isn't a good solution if you're trying to do array
slices, i.e., a parenthesized list on the right of the "=".

> Everything in zsh I've tried around  ${${(P)v}[2]::=cherry}  with misc different bracketing gets "not an identifier", suggesting maybe the ::= form doesn't support subscripting.

It's not that it doesn't support subscripting, it's that it doesn't
support parameter expansions of any kind on the left:

% echo ${${grape}::=raisin}
zsh: not an identifier:

I'm not sure why the error isn't more specific.

The syntax, if it worked, would be ${(P)v[3]::=cherry}, because
${(AP)=v::=apple banana carrot} works, but although ${(P)v} gets you a
reference to $fruits, as soon as you subscript it as ${(P)v[x]} you
end up assigning to a copy of the x'th field of $fruits instead,
because zsh doesn't create indirect references to array elements, it
substitutes them by value.

You can do it this way:

echo ${(P)z::=cherry}

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