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

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



2024-01-18 18:58:41 -0800, Ray Andrews:
> 
> On 2024-01-18 18:46, Bart Schaefer wrote:
> > On Thu, Jan 18, 2024 at 3:08 PM Ray Andrews <rayandrews@xxxxxxxxxxx> wrote:
> > > How hard would it be to get the first hash 'right'?
> > That's not how hash tables work.
> 
> I have no idea how they work which is why my comments have little value.  If
> ksh can do it then it can be done, but as I said, it simply might not be
> worth the effort and I'm in no position to judge the matter.  I wish I'd
> gotten that far in C, I'd heard of hash tables but never coded one.  But I
> did note in that code previous that the order seemed not to change. 
> Nevermind.

As said before, in "${!hash[@]}", ksh93 orders the keys
lexically, not in the order they were inserted in the hash
table. It doesn't record that order either.

If you want to do the same in zsh, use the o parameter expansion
flag to order the keys. See also n to order numerically:

$ ksh -c 'typeset -A a; for i do a[$i]=$(( ++n )); done; printf "%s\n" "${!a[@]}"' ksh {1..20}
1
10
11
12
13
14
15
16
17
18
19
2
20
3
4
5
6
7
8
9

$ zsh -c 'typeset -A a; for i do a[$i]=$(( ++n )); done; printf "%s\n" "${(ko@)a}"' ksh {1..20}
1
10
11
12
13
14
15
16
17
18
19
2
20
3
4
5
6
7
8
9
$ zsh -c 'typeset -A a; for i do a[$i]=$(( ++n )); done; printf "%s\n" "${(kn@)a}"' ksh {1..20}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

-- 
Stephane




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