tags:

views:

184

answers:

1

I know that the names returned by [array names X] are in an undefined order, but are they always in the same undefined order?

I'm going through a very large array, and would like to log progress to a file in case of a crash, so I can resume part-way through again.

PS. A quick experiment implies it is always the same 'random' order, but this doesn't mean it's true!

+5  A: 

The short answer is that you can't rely on the order and your best bet is to [lsort [array names X]] and use that order.

The long answer is that the order should be stable as long as the keys are the same (and its the same Tcl version)... but I still wouldn't rely on it.

If you're using Tcl 8.5 or later, you might want to look at using a Dict instead of an array. The order of elements for a Dict is the order they were added in.

RHSeeger
Agh - 8.4!Thanks a lot.
Cormac
The good news is that while dict isn't a standard part of 8.4 you can load it as a package. See http://wiki.tcl.tk/5042
Jackson
You could even write your own proc for lsort so you can force a different order than purely alphabetical, if that matters.
Michael Mathews
The order of keys is not guaranteed at all; it depends not just on the order that they were added, and the internal details of the hash function, but *also* on the history of any additions to and removals from the array (especially if they've caused a rehash). Plus you can encounter problems if there are traces set on the array that modify it; the `env` array is particularly bad this way. Treat the order as random and you won't go wrong.
Donal Fellows