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

Re: Implement an "array index" subscript flag



I like this solution. If we change (k) to work with arrays, then it sounds like it would allow the bash ${!array[@]} syntax to work identically, which is another benefit.


Although incidentally, I don't have any success using (k) even with associative arrays. Perhaps I'm misunderstanding? This produces no output:

arr=([1]=a [2]=b)
keys=${arr[(k)@]}
echo $keys


My only other concern is that it sounds like (k) actually does pattern matching to look up the index of each value. Does this have performance implications? Would it not be simpler to just return the underlying array positions (depending on how arrays are implemented)?

________________________________
From: dana <dana@xxxxxxx>
Sent: Friday, 8 June 2018 3:16 PM
To: zsh-workers@xxxxxxx
Cc: Michael Milton
Subject: 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