1

I've got a hash with keys of the following form: A23, A03, A200, etc.

As I understand it, keys in a hash are not exactly sequential. If I build the hash by first adding A23, A03, and A200, then I can't be sure they will be in that order when I iterate over the hash - correct?

How would I be able to loop from one key in a hash, to another key, visiting the keys in "added" order. If there is no such thing as "added" order with hashes, then I could sort the keys alphabetically.

2 Answers2

1

Perl doesn't track added order for hashes, so you'll either have to track that seperately, or just fall back to alphabetical. for my $key (sort keys %hash) {...} is the gist of what you're looking for.

ricecake
  • 71
  • 3
-2

Yes, key insertion order is not maintained. For a module based solution , see http://search.cpan.org/~chorny/Tie-IxHash-1.23/lib/Tie/IxHash.pm

Or you can build an index into your key and sort on retrieval:

%hash = (
    '01:A23' => 1,
    '02:A03' => 2,
    '03:A200' => 3
);

foreach $one_key (sort keys %hash ) {

    print("KEY : $one_key  VALUE :$hash{$one_key}\n");
}

Output is:

KEY : 01:A23  VALUE :1
KEY : 02:A03  VALUE :2
KEY : 03:A200  VALUE :3
Kim Ryan
  • 515
  • 1
  • 3
  • 11