help / color / mirror / code / Atom feed
From: Bart Schaefer <schaefer@brasslantern.com>
To: Anthony Heading <ajrh@ajrh.net>
Cc: Zsh Users <zsh-users@zsh.org>
Subject: Re: indirect array element assignment?
Date: Sat, 2 Jul 2022 11:13:57 -0700	[thread overview]
Message-ID: <CAH+w=7YCZDE3OCFakdGfxEptnM=8zwvG3PBEH-FnSi+=oTM7pA@mail.gmail.com> (raw)
In-Reply-To: <11ca04c9-1503-4cd2-a44b-635dc53e43a8@www.fastmail.com>

On Sat, Jul 2, 2022 at 3:34 AM Anthony Heading <ajrh@ajrh.net> 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}

  reply	other threads:[~2022-07-02 18:15 UTC|newest]

Thread overview: 6+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2022-07-02 10:33 Anthony Heading
2022-07-02 18:13 ` Bart Schaefer [this message]
2022-07-02 18:23   ` Bart Schaefer
2022-07-03  2:28   ` Anthony Heading
2022-07-03  3:41     ` Bart Schaefer
2022-07-03 16:43       ` Anthony Heading

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to='CAH+w=7YCZDE3OCFakdGfxEptnM=8zwvG3PBEH-FnSi+=oTM7pA@mail.gmail.com' \
    --to=schaefer@brasslantern.com \
    --cc=ajrh@ajrh.net \
    --cc=zsh-users@zsh.org \


* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
Code repositories for project(s) associated with this public inbox


This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).