help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] Smart determination of array or associative array based


From: Eli Schwartz
Subject: Re: [Help-bash] Smart determination of array or associative array based on the first key
Date: Sun, 13 Oct 2019 14:56:46 -0400
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Thunderbird/68.1.1

On 10/13/19 2:04 PM, Peng Yu wrote:
> Bash currently can not use the value of the first key to automatically
> determine whether an array or an associative array should be
> initialized.
> 
> $ x[xxx]=s
> $ declare -p x
> declare -a x=([0]="s")
> 
> In the above example, I'd like `declare -A x` be implicitly called
> before `x[xxx]=s` as the key `xxx` is not a number.
> 
> I think this feature makes sense because when `xxx` (which is not a
> number) is used as the first key, the programmer almost always intends
> to use `x` as an associative array instead of an array. Could this
> feature be added to bash? Thanks.

That's terrifically dangerous, and bash is already dangerous enough
without adding more traps like this. You've misunderstood what is
happening here.

$ unset mykey myarray
$ mykey=22
$ myarray[mykey]=s
$ declare -p myarray
declare -a myarray=([22]="s")

Inside the assignment "x[xxx]=s", the xxx is being evaluated via
arithmetic evaluation, the most likely uset variable is being
interpreted as equal to 0:

$ unset xxx
$ echo $(( xxx ))
0

And then x[0] is resolved and assigned.

This should not be conditional on whether the key happens to be assigned
as an integer. Just declare your types. Don't try to make bash "guess
what you mean", that just leads to it guessing... wrongly.

-- 
Eli Schwartz
Arch Linux Bug Wrangler and Trusted User

Attachment: signature.asc
Description: OpenPGP digital signature


reply via email to

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