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

Re: Empty element elision and associative arrays (was Re: Slurping a file)




On 2024-01-14 16:55, Bart Schaefer wrote:
On Sun, Jan 14, 2024 at 4:03 PM Ray Andrews <rayandrews@xxxxxxxxxxx> wrote:
When assigning to an associative array ...

% typeset -A asc=( $something )

... the expansion of $something has to yield an even number of
"words", yes.  But remember the previous lesson about those outer
parens -- they only mean that the thing to the left is an array, they
don't matter to what's inside those parens.  So if $something is an
array with empty elements, those elements are going to be elided,
which might leave you with an odd number of words and break the
assignment -- or possibly worse, turn some values into keys and some
keys into values.

Exactly as I understand it.  A arrays are 'not very clever' -- they don't try to protect you from yourself, there's no internal place holding for a missing value, and as you say things must be kept to pairs. 

(output may vary because associative arrays are not ordered).
I've noticed that.  One  might think that the order of assignment would be 'the order' by inevitability, but that seems not to be the case.  I don't understand how it could be otherwise but nevermind.
Returning to the original example, that means if  you're copying one
associative array to another, you need to copy both the keys and the
values, and quote it:

% typeset -A asc=( "${(@kv)otherasc}" )

You said something the other day that was important: the parens do not say 'I am an array' they say 'turn me into an array'  it's one of those things that must be clear. 

Yeah, I'm getting somewhat competent with A's.  They're not very forgiving but the rules aren't that hard to remember. 




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