Zsh array -a vs. -A question

Inside a zsh function, I create a local array with

local -a arrayname

and a local associative array with

local -A arrayname

.

I also can create an array using set, like this:

set -A arrayname value1 value2 value3

In this form, I can not explicitly declare that an array is associative or non-associative (

set -a

exists, but has a completely different meaning).

Does someone know why this distinction was made?

local is the same as typeset and it is a declaration. Set is an assignment to the array. To use associative arrays, typeset (declaration) must be done beforehand.. With regular arrays declaration is optional.

% set -A arr red 1 blue 2
% echo ${arr[red]}

% typeset -A arr
% set -A arr red 1 blue 2
% echo ${arr[red]}       
1
% echo ${arr[blue]}
2
2 Likes

Comparison with bash4

$ typeset -A arr
$ arr=( [red]=1 [blue]=2 )
$ echo ${arr[red]}
1
$ echo ${arr[blue]}   
2