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

Re: Splitting into a one element array



Ah yes, now I see. Thank you both!


On Mon, Sep 14, 2015 at 11:46 PM, Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx>
wrote:

> On Sep 14, 10:06pm, Jesper Nygards wrote:
> } Subject: Splitting into a one element array
> } I am writing a function where I want to split the $LBUFFER on whitespace,
> } and then handle the last element in the resulting array. My initial
> attempt
> } looked like this:
> }
> } local dir=${${(z)LBUFFER}[-1]}
> }
> } This works if $LBUFFER contains more than one word, but fails if it is
> one
> } word only.
>
> Yes, this is a side-effect of nested expansion working "inside out"; if
> if there's nothing for ${(z)...} to split, the result becomes a scalar
> before the context one level up is even considered.
>
> For the case of splitting on spaces you can fix this with a subscript
> flag as in ${LBUFFER[(w)-1]}, but because (z) splits on syntax rather
> than on spaces there's no simple corresponding flag for "subscript on
> shell words".
>
> So the most readable way is probably the local array that ZyX suggested,
> but if you really want a single nested expansion:
>
>     ${${(z)LBUFFER}[(wps:$'\0':)-1]}
>
> This works because the subscript flag [(w)] is only active when applied
> to a scalar, so (ps:$'\0':) only applies when (z) returns a single word,
> which won't contain a $'\0' byte so is not split further.
>


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