Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > gnu.bash.bug > #15128 > unrolled thread

Feature request: alternating keys & values syntax for hashes

Started bySebastian Gniazdowski <sgniazdowski@gmail.com>
First post2019-07-10 20:12 +0200
Last post2019-07-10 20:12 +0200
Articles 1 — 1 participant

Back to article view | Back to gnu.bash.bug

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Feature request: alternating keys & values syntax for hashes Sebastian Gniazdowski <sgniazdowski@gmail.com> - 2019-07-10 20:12 +0200

#15128 — Feature request: alternating keys & values syntax for hashes

FromSebastian Gniazdowski <sgniazdowski@gmail.com>
Date2019-07-10 20:12 +0200
SubjectFeature request: alternating keys & values syntax for hashes
Message-ID<mailman.864.1562786242.2688.bug-bash@gnu.org>
Hello
The current syntax for hashes doesn't allow interaction between arrays
and hashes. The syntax that would allow it is simple dump of the keys
and values alternating and acceptance of such series of values at
assignment of the hash.

This syntax is long used in Zsh. Example code:

declare -a array=( a 1 b 2 c 3 )
declare -A hash=( ${array[@]} )
declare -p hash
=> typeset -A hash=( [a]=1 [b]=2 [c]=3 )
declare -a array2=( ${(kv)hash[@]} )
declare -p array2
==> typeset -a array2=( a 1 b 2 c 3 )

This has many useful use cases e.g. when doing an advanced, fork-(i.e.
also: subshell) free shell coding. Consider e.g. a fork-free
serialization of an array:

array=( val1 "val2*[special-chars]" )
printf -v serialized "%q " "${array[@]}"
eval "deserialized=($serialized)"

With the new syntax it would be possible to serialize and deserialize
hashes in the same way (the *-char is the example new syntax to dump
k&v alternating):

declare-A hash=( [key1]=val1 ['key2*[special-chars]']=val2 )
printf -v serialized "%q " "${*hash[@]}"
typeset -A deserialized_hash
eval "deserialized_hash=($serialized)"

This is a one particular example use case, but I'm using array<->hash
interaction on a regular basis in Zsh.

The syntax-extension is of most-easy kind, it actually doesn't change
anything (besides the *-like addition to the var flags, i.e. the
${*hash[@]}, to dump k&v-s), it's just about allowing hashes to accept
series of values, being the k&v-s alternating. Is there a chance for
such an extension?

PS. The *-symbol might be the right choice, as it inherits the glob
meaning "match all", and this translates to the hash variable "give
back all, i.e. values AND keys".

--
Sebastian Gniazdowski
News: https://twitter.com/ZdharmaI
IRC: https://kiwiirc.com/client/chat.freenode.net:+6697/#zplugin
Blog: http://zdharma.org

[toc] | [standalone]


Back to top | Article view | gnu.bash.bug


csiph-web