Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Help with associative arrays

> On Aug 21, 2016, at 4:50 PM, Vin Shelton <ethersoft@xxxxxxxxx> wrote:
> I can't seem to figure this out.  I'm trying to use an associative
> array and the results are not what I expect:
> #!/usr/bin/env zsh
> emulate -LR zsh
> typeset -A repos
> repos["conky"]="https://github.com/brndnmtthws/conky.git";
> nickname="conky"
> echo "nickname = " \"$nickname\" "repos = " \"${repos[$nickname]}\"
> echo "nickname = " \"$nickname\" "repos = " \"${repos["conky"]}\"
> yileds:
> nickname =  "conky" repos =  ""
> nickname =  "conky" repos =  "https://github.com/brndnmtthws/conky.git";
> given that nickname is "conky" I expected the values to be the same.

From zshparam(1):

        The basic rule to remember when writing a subscript expression
        is that all text between the opening `[' and the closing `]' is
        interpreted as if it were in double quotes (see zshmisc(1)).


        The second difference is that a double-quote (`"') may appear as
        part of a subscript expression without being preceded by
        a backslash....

The double quotes you're using are not acting as quoting syntax; they
are being treated literally and are becoming part of the key itself.

	% typeset -A repos1; repos1["conky"]=foo; typeset repos1
	repos1=( '"conky"' foo )
	% typeset -A repos2; repos2[conky]=foo; typeset repos2
	repos2=( conky foo )

But the quotes are behaving as you expect when you do the assignment to

	% nickname="conky"; typeset nickname

So $repos[$nickname] is evaluated as $repos[conky], not $repos["conky"],
while your array contains a '"conky"' key, not a 'conky' key. In the
end, you're not looking up the key you want.

tl;dr: Don't use double quotes in array subscripts, unless your array
contains keys with literal double quotes.


Messages sorted by: Reverse Date, Date, Thread, Author