With ksh93, typeset -a arr=( () )
will create arr[0]
as an empty compound var rather than an empty indexed array:
$ typeset -a arr=( () )
$ typeset -p arr[0]
typeset -C arr[0]=()
$
So how can I init arr[0]
to an empty indexed array when declaring the arr
var?
$ ( typeset -a a[0]=(); typeset -p a 'a[0]' )
typeset -a a=( () )
typeset -a a[0]
I don't think anybody knows for sure. I asked whether someone could explain some of the logic behind ksh's seemingly random declarations in your thread and never got a reply.
I believe the explanation for this specific issue is that it's a mistake to think about multidimensional indexed arrays as "nestable" even though the syntax strongly suggests it. The entire array is all one type, so once the array has been declared, you can't separately set an "empty collection" as the zeroth element. The only real nestable types are compounds, so by attempting to create a vector at a[0]
without at least assigning an empty string to a[0][0]
, it assumes it must be compound.
To put it another way, typeset -a a
sets the type of a
and all sub-elements at once, so you can just go ahead and start adding values to the higher dimensions since they can't possibly have separate attributes without being compound.
I think the syntax above is just a loophole that allows setting the attribute that would implicitly apply to the sub-elements of a
anyway. Notice even if I declare it like you did, appending values to the array using indexed assignment syntax automatically reverts the type back to indexed, (because a compound would be expecting declaration commands or assignments as elements).
$ ( typeset -a a=( () ); typeset -p a 'a[0]'; a[0]+=(x y z); typeset -p a 'a[0]' )
typeset -a a=(())
typeset -C a[0]=()
typeset -a a=(([1]=x [2]=y [3]=z) )
typeset -a a[0]=([1]=x [2]=y [3]=z)
Of course, there are still many things I don't understand. LMK if you find anything particularly interesting. :) I think we're about the only ones using these features... Damn near impossible finding example code.
Also, I've started documenting some ksh/bash/zsh-style array comparisons here.
I found a hacking way with newer versions (tried with 93v- 2013-02-13
) of ksh:
$ echo ${.sh.version}
Version AJMP 93v- 2013-02-13
$ typeset -p arr
$ typeset -a arr=( ( ${not_existing_array[@]:0:0} ) )
$ typeset -p arr
typeset -a arr=( () )
$ typeset -p arr[0]
typeset -a arr[0]
$
That's kind of reasonable as an empty subset of an indexed array is still an indexed array. :)