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

Re: array element subsetting

On Mar 26, 12:32pm, S. Cowles wrote:
} Subject: Re: array element subsetting
} On Fri, 26 Mar 2010, Bart Schaefer wrote:
} > 	print ${(e):-'${${=:-'${^a}' ""}[2]}'}
} I hadn't previously used the parameter expansion (e) or array creation
} ${=...} methods. The inline array element addition is new to me; I
} missed it in Peter's Manual, book, and the zshall man page.

It isn't really "inline array element addition" -- it's just adding a
space and a pair of empty quotes to the end of a string.  What turns
it into an array element is the combination of ${(e)...} which expands
the ${=:-...} expression and thereby removes the quotes, and ${=...}
which splits on the space.

The important bit is the ${^a} wedged in the middle, which turns the
array of strings into an array of parameter expressions wrapped around
those strings.  This is not a very space-efficient way to emulate a
multi-dimensional indexing, even if it's compact to write.
} Would it be worth considering adding a new subsection on Array
} Subsetting to the ARRAY PARAMETERS section of the man pages [...]?

I'm not sure it's a common enough thing to want to do in shell code
to be enshrined in the manual, but I'll defer that decision to PWS.
I'd suggest it go in the FAQ except I don't recall it ever having
been asked before, so the "frequent" part hardly applies ...

Incidentally, one might wonder why

	print ${(e):-'${${:-'${^a}'}[(w)N]}'}

doesn't work.  The manual says:

     If the parameter subscripted is a scalar then this flag makes
     subscripting work on words instead of characters.  The default
     word separator is whitespace.

The answer is that it does work, as long as the value of N is less
than the number of words in any string.  However, the result of
${three_word_string[(w)4]} is the last word in the string, not an
empty element as results with ${${=three_word_string}[4]}.

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