bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Feature request: alternating keys & values syntax for hashes


From: Sebastian Gniazdowski
Subject: Feature request: alternating keys & values syntax for hashes
Date: Wed, 10 Jul 2019 20:12:05 +0200

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



reply via email to

[Prev in Thread] Current Thread [Next in Thread]