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

Re: How to iterate over an array of associative arrays



On Jul 14,  3:36pm, Thorsten Kampe wrote:
}
} > > AssocArr1=(key value1)
} > > AssocArr2=(key value2)
} > >
} > > array=($AssocArr1 $AssocArr2)
} > 
} > Do you really want these $ here?
} 
} Yes, I really wanted to pass the actual associative arrays, but if I can 
} pass the names that's fine with me, too.

The shell language is text-oriented and can be though of as strictly
pass-by-value, so there's no way to create a nested data structure; the
values of the array cannot be direct references to other arrays.

} > You need to use the (P) flag to access a parameter indirectly.

Ksh namerefs, which are partly emulated by zsh's (P) flag, allow you to
simulate references but are not true object handles.

} Doesn't work for me:
} 
} """
} array=(AssocArr1 AssocArr2)
} 
} for elem in $array
}     do echo ${${(P)elem}[key]}
} done
} """

Unfortunately even though ${(P)elem} can access by reference, it can only
"return" (expand that reference) by value, and the shell has only two kinds
of values: strings or plain arrays.

Fortunately, although associative array keys/values are not maintained in
any predictable order, they are guaranteed to be returned in a consistent
order (as long as no new elements are inserted between accesses) so this
can be done:

"""
declare -A AssocArr
AssocArr=(key1 value1 key2 value2 key3 value3)
ref=AssocArr

print position of key2 is ${${(kP)ref}[(i)key2]}
print value for key2 is ${${(P)ref}[${${(@kP)ref}[(i)key2]}]}
"""

The extra (@) in there is because $arr[key] puts key in double-quoted
context, so you have to force ${(P)ref} to remain an array for the
subscript operation.



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