bug-bash
[Top][All Lists]
Advanced

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

Re: feature request array expansion of keys values pairs and for k v loo


From: Koichi Murase
Subject: Re: feature request array expansion of keys values pairs and for k v loop
Date: Thu, 19 Aug 2021 11:48:27 +0900

2021年8月19日(木) 9:31 Léa Gris <lea.gris@noiraude.net>:
> [...]
>
> I'd like some syntax to expand both keys and values into a single
> scalar. Something like a at sign or another symbol meaning both are
> expanded:
>
> # Expand key values pairs as distinct arguments
> printf '%s ' "${@array[@]}"
> printf \\n

FYI, zsh provides this feature for associative arrays with the syntax
${(kv)assoc} or ${(@kv)assoc}. Note that Bash-5.1 already has a
similar feature ${array[@]@K}, but the substitution result is quoted
so cannot be directly used for the present purpose. To fit the Bash
syntax for the substitution attributes, it might be ${array[@]@kv},
${array[@]@k}, or something if it would be supported in Bash.

> Consequently it could allow expanding the for loop with:
> for k v in "${@array[@]}"; do
>    printf 'Key=%s\tValue=%s\n' "$k" "$v"
> done

One ambiguity arises with this approach when the user wants to specify
`in' as the variable name. In the current grammar, the following
construct is valid and unambiguous because the keyword `in' can only
appear as the second word of the arguments of the for statement.

for in in in in in; do echo "<$in>"; done

However, if we are to accept multiple variable names in the for
statement, the keyword `in' doesn't necessarily appear as the second
word so that there are two possible interpretations:

- FOR [variable-name "in"] IN [word "in"] [word "in"] [word "in"]
- FOR [variable-name "in"] [variable-name "in"] IN [word "in"] [word "in"]

zsh implements this multiple variable names in for statements. zsh
seems to have chosen the first behavior according to my quick test.

--
Koichi



reply via email to

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