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

Re: Unsetting Array

On Tue, Dec 09, 2008 at 02:18:34PM +0000, Peter Stephenson wrote:
> "Jerry Rocteur" wrote:
> > I'm using ZSH_VERION 4.2.6 on Redhat 5 to test some Korn shell scripts.
> > 
> > Note that /usr/bin/ksh is a link to /bin/zsh
> > 
> > I am unsetting an array like this unset variable[$i] and get
> >..
> > What is the correct way to unset an array element.
> You can't strictly *unset* an element to an array.  In zsh, an array is
> always a set of strings that has a particular length.  So what you can
> do is limited to changing the length of the array or setting an element
> of the array to be an empty string.  The latter is probably nearest to
> what you want, but (in places where it makes a difference) the shell
> will always treat the empty element as a string with zero length, not as
> an unset parameter.  The syntax for that is
>   variable[$i]=

Yes, contrary to ksh, zsh arrays are not sparse arrays but
normal arrays as for instance in C (though indices start at 1,
not 0). You could implement a sparse array with an associative

Another thing to be aware of is that $array in zsh expands to
the non-empty elements of the array.

~$ a[5]=foo
~$ printf '<%s>\n' $a
~$ printf '<%s>\n' "$a[@]"


declares an array of 100000 elements, all of them empty.

But you could do:

typeset -A a

Which would declare an associative array with only one element
of key "100000" (beware 100000 is a string)

"$a[@]" would then expand to the list of values (here only one
empty value) but beware that you cannot guarantee the order in
which the values will be displayed.


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