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

Re: array element subsetting

On Mar 26,  2:24am, S. Cowles wrote:
} I am trying to figure out the correct syntax for constructing two 
} one-liner subsetting operations on arrays.  I have two objectives: 1) 
} select nth character from each array element, and 2) select nth element 
} within each array element.
} The array these methods operate upon is something simple such as:
} a=(
}      "satu two trio"
}      "sah funf seis"
}      "boundarycase"
}      "revert to pattern"
} )

(1) can be done with the (M) parameter flag and simple head/tail:

	print ${(M)a#?}

To generalize to the Nth element, ${(M)${(M)a#?(#c$N)}%?} (requires
extendedglob, of course).

(2) is more difficult to do without looping, because zsh doesn't
support multidimensional arrays, so you have to force an eval step
via the (e) flag:

	print ${(e):-'${${=:-'${^a}'}[2]}'}

However, this yields the second character of arrays that contain
only one word, because ${=...} reduces singular arrays to scalars.
A simple workaround is to insert an empty dummy element at the tail:

	print ${(e):-'${${=:-'${^a}' ""}[2]}'}

In the event there are special characters in the strings in $a, an
extra level of quoting can be added and then removed:

	print ${(e):-'${${=${(Q):-'${(q)^a}' ""}}[2]}'}

However, this removes again the empty element inserted by the double
quotes, i.e., it returns nothing for the short array rather than an
empty second element (use "print -l" in those examples to see the
difference more clearly).  Remove the (e) if you want to see what's
going on with the ${(q)^a} business.

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