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

Re: Implement an "array index" subscript flag



On 7 Jun 2018, at 20:37, Michael Milton <michael.milton@xxxxxxxxxxxxxx> wrote:
>A useful feature for zsh would be the ability to convert an array into an array
>of keys/indexes for that array.... Bash has a syntax for this, with the
>${!array[@]} expansion

zsh actually has the (k) flag for this, but it only works on associations. zsh
also supports the ! syntax (which bash 3 borrowed from ksh93) when in ksh-
emulation mode, but since it's effectively an alias for (k) it *also* works only
on associations. To be clear, in both bash 4 and ksh93 it works as expected on
both.

I feel like the intuitive thing would be for (k) and (v) to work on arrays
equivalently to the way they work on associations. In other words...

  % arr=( foo bar baz )
  % print ${(k)arr}
  1 2 3
  % print ${(kv)arr}
  1 foo 2 bar 3 baz

Looking at the manual, it seems to me that the current effect of those two flags
on arrays is actually undefined (except when used in conjunction with a
subscript), so... would that not be a reasonable change to make, if someone were
inclined?

Looks like Oliver was considering exactly that, once upon a time:
http://www.zsh.org/mla/workers/2004/msg00226.html

In the mean time, though, like the Stack Exchange link says — since zsh doesn't
support sparse arrays, i think {1..$#arr} is almost exactly equivalent to (the
hypothetical) ${(k)arr}.

dana



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