bug-bash
[Top][All Lists]
Advanced

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

Re: No expansions performed while declaring an associative array using a


From: Glenn Jackman
Subject: Re: No expansions performed while declaring an associative array using a list of keys and values
Date: Tue, 15 Dec 2020 11:23:00 -0500
User-agent: Mutt/1.10.1 (2018-07-13)

On 2020-12-11 11:41, Chet Ramey wrote:
> I agree that it would be useful to have
> 
> foo='1 2'
> declare -A v1=$( $foo 3 )
> declare -A v2=$( [$foo]=3 )
> 
> set the two arrays to the same contents

I would think that these pairs of invocations would correspond:

    declare -A v1=$( $foo 3 )
    declare -A v1=$( [1]=2 [3]="")

    declare -A v1=$( "$foo" 3 )
    declare -A v1=$( ['1 2']=3 )

Do word splitting and quote removal not occur within the parentheses of an
_associative_ array definition?

As the manual states:

> When assigning to an associative array, the words in a compound assignment
> may be either assignment statements, for which the subscript is required,
> or a list of words that is interpreted as a sequence of alternating keys
> and values: name=(key1 value1 key2 value2 … ). These are treated
> identically to name=( [key1]=value1 [key2]=value2 … ). 

They do not appear to be treated identically:

    $ declare -A name=( [foo]=bar [baz]="hello world" )
    $ declare -p name
    declare -A name=([foo]="bar" [baz]="hello world" )

but with a key-value list, the quotes are preserved:

    $ declare -A name=( foo bar baz "hello world" )
    $ declare -p name
    declare -A name=([foo]="bar" [baz]="\"hello world\"" )



I'd love to be able to read a key-value list from a CSV file, like

    $ line="foo,bar,baz,hello world"
    $ enable -f csv csv
    $ csv "$line"
    $ declare -A assoc
    $ assoc=( "${CSV[@]}" )

But, as previously stated, the whole array is taken as a single key

    $ declare -p assoc
    declare -A assoc=(["foo bar baz hello world"]="" )

There's a workaround using `eval` and shell-quoted transformation, 
but ... yuck:

    $ eval assoc=( "${CSV[@]@Q}" )
    $ declare -p assoc
    declare -A assoc=([foo]="bar" [baz]="hello world" )

Particularly when this same technique works for indexed arrays: this results in
a copy of the CSV array, not a new array with only a single element:

    declare -a copy
    copy=("${CSV[@]}")




-- 
Glenn Jackman
    Write a wise saying and your name will live forever. -- Anonymous



reply via email to

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