in reply to hash property

As pg noted, a hash has no order (or actually, what may seem at times like random order, though few things with computers are purely random unless you're talking about mouse-click-sequences required to crash Windows).

If you really need your hash to be sorted in a particular way, you can do that with a module like Tie::IxHash. Be forewarned that you use such approaches at the cost of considerable performance degredation.

Another solution is to keep track yourself of the hash keys as they are created. Take the following example:

use strict; use warnings; my (%hasharr, @hashkeys, $start); while ( my $line = <> ) chomp $line; next unless $line; #skip empty lines. my ($head, $prod) = split /\s*:=\s*/, $line; foreach ($head, $prod) { s/^\s+//; s/\s+$//; } unless ( $start ) { $start = $head; }; push ( @{$hasharr{$head}}, $prod); push @hashkeys, $head; }

Yes, you're using a little more memory than before, because now you're maintaining a separate array of keys, in insertion order. But let me say that again, you have an array containing a list of keys in insertion order! Bingo. And as long as you're diligent about keeping the array and the hash in synch with each other, life is good. This approach won't scale as well as the Tie::IxHash method, but it is faster.

Also note, my code snippet provides you with a few altered idioms for you to consider. They may not be exactly what you need, but they are "yet another way to do it". Especially regarding my method of eliminating the "$bool" variable, understand what's going on before copying my example, because it is functionally different if my implicit assertion (that $start is non-true, or empty, while $bool is non-true) is invalid.

One more thing. Notice my use strict; and use warnings;. They are "A Very Good Idea" almost always (I'll stop short of "always"). And an even better idea for code that uses complex data structures (like yours), as they'll prevent you from accidentally using symbolic references, among other common pitfalls.


Dave


"If I had my life to do over again, I'd be a plumber." -- Albert Einstein

Replies are listed 'Best First'.
Re: Re: hash property
by Anonymous Monk on Oct 15, 2003 at 06:05 UTC
    thanks gentleman for all your help...i realized that i could solve my problem without ordering the hash in a certain way. However, your answers provided me with much insight.