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

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