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

Re: indirect array element assignment?



On Sat, Jul 2, 2022 at 7:28 PM Anthony Heading <ajrh@xxxxxxxx> wrote:
>
> On Sat, Jul 2, 2022, at 2:13 PM, Bart Schaefer wrote:
> > 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:
>
> Ah, that makes sense.  Though hmm...  there's some lhs expansion, no?
> ${grape[$#grape]::=raisin} for example.

Subscripting does expansion inside the [ ], but that's not the same
context as ${${...}}.

> Is it a necessary error by design?  ... for lhs ::= I wonder
> why ${${X}::=...} couldn't have well-defined natural meaning.

For that to work, ${${X}} would have to mean the same as ${(P)X}.  As
a general rule nested expansions are processed innermost-leftmost, and
substitute rvalues rather than lvalues.  The (P) is what forces the
current level of expansion to turn into an lvalue, but that doesn't
apply to either the surrounding or the surrounded levels.

So ${(P)${X}::=thing} actually does work as long as ${X} returns a
valid identifier that can be treated as an lvalue.  Without the (P) it
remains an rvalue and you get the "not an identifier" error.

(I'm glossing over a lot of what actually goes on underneath here, but
if you're familiar with the concepts of lvalues and rvalues this is a
pretty good way to think about it.)

That does in fact mean that this works too, now that I think of it:

${(P)${:-${v}[2]}::=mango}

> > 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 "=".
>
> You're referring to the typeset style solution here, maybe?

Yes.

> Your later solution seems to work great for all sorts of array splicing.

Sure, but you also have to do your own array splitting, as e.g.
${(AP)=v::=apple banana carrot}, if attempting to assign a plain list
of words.




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