in reply to Order a hash?

A minor distinction - hashes do have a specific order, it is just that the order is internal to perl and usually makes no sense to us. (Perl does this on purpose, to make the hash lookup as fast and efficient as possible). More importantly, the order that a hash is in may look random, but it is the same random every time the hash is called (and as long as you don't change the hash). In other words, all calls to keys, values, and each will always return the elements of the hash (keys, values, or both) in the same order. Sorting, as mentioned above, is a great way to sort out your keys in a hash: "sort keys %hash" is a very common construct. Arrays are always ordered, but require you to access it by using a number. Hashes allow you to access it by any name you want, with the drawback of not having any sort of order, as you have discovered. Play with both, and try converting from one to another to get a good feel for them. There are lots of examples on this site, and of course, feel free to post questions here as well.

Replies are listed 'Best First'.
Cache Sorts? RE:(2) Order a hash?
by Adam (Vicar) on Jul 20, 2000 at 20:37 UTC
    Out of mild curiosity, does Perl do any caching of a sort keys %hash call, or do you have to do that yourself? (And if so, when does it become worth it? How many repeated calls of sort keys %hash does it take until my @sortedkeys = sort keys %hash becomes a worthwhile use of memory? 1? 2? Never? I don't think that I've ever written a script that needed to sort the same thing more then once, and if I did I probably cached the results in an array first, but I'm wondering if Perl does any optimization there...