OILS / spec / assoc-zsh.test.sh View on Github | oilshell.org

53 lines, 25 significant
1#
2# Differences from bash:
3# - literal syntax alternates key-value
4# - (@k) syntax for keys. Although this is sort of like my ${@array} syntax
5# for arrays.
6# - zsh allows $a[$k], not just ${a[$k]}
7
8
9#### TODO: SETUP should be shared
10typeset -A a
11a=(aa b foo bar a+1 c)
12
13#### retrieve key
14typeset -A a
15a=(aa b foo bar a+1 c)
16echo ${a[aa]}
17## stdout: b
18
19#### set key
20typeset -A a
21a=(aa b foo bar a+1 c)
22a[X]=XX
23argv.py "${a[@]}"
24# What order is this?
25## stdout: ['bar', 'b', 'c', 'XX']
26
27#### iterate over keys
28typeset -A assoc
29assoc=(k1 v1 k2 v2 k3 v3)
30for k in "${(@k)assoc}"; do
31 echo "$k: $assoc[$k]"
32done
33## stdout-json: "k1: v1\nk2: v2\nk3: v3\n"
34
35#### iterate over both keys and values
36typeset -A assoc
37assoc=(k1 v1 k2 v2 k3 v3)
38for k v ("${(@kv)assoc}"); do
39 echo "$k: $v"
40done
41## stdout-json: "k1: v1\nk2: v2\nk3: v3\n"
42
43#### get length
44typeset -A assoc
45assoc=(k1 v1 k2 v2 k3 v3)
46echo ${#assoc} ${#assoc[k1]}
47## stdout: 3 2
48
49#### index by integer does not work
50typeset -A assoc
51assoc=(k1 v1 k2 v2 k3 v3)
52argv.py "${assoc[1]}"
53## stdout: ['']