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

Re: Writing to an indirectly named array...



[Cc zsh-users on private reply, hope that's OK]

On Jan 1,  7:50am, meino.cramer@xxxxxx wrote:
}
} >     set -A $nameofarray elem1 elem2 ...
} 
} ...is there another way by using the (P)-notation somehow ?

Yes, but it still doesn't get you things like array+=(elems) or
array[N]=(elems), and it's a little more difficult to get the
elements split the way you may want them.

    : ${(PA)=nameofarray::=elem1 elem2 ...}

This says to dereference namaofarray and then assign the result of
the ::= operator as an array.  The shwordsplit (=) operator applies
across the whole assigment so elem1 elem2 ... are split as well.
If you don't want that semantics, you can apply an explicit split
to the right side, e.g.,

    print file has ${(PA)#nameofarray::=${(f)"$(<file)"}} lines
    print the fifth line is ${${(P)nameofarray}[5]}

You actually can poke into the middle of an array using the (P) form
but it's rather convoluted and probably error-prone:

    local thefifthelement="$nameofarray"'[5]'
    : ${(PA)=thefifthelement=three new elements}

That is, you include the subscript expression in the value of the
parameter that you then dereference with (P).  This works for anything
that could normally appear on the left side of an assignment.



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