Is it possible to iterate through a hash in sorted order using the while(my($key, $value) ... ) {} method?

Vidur picture Vidur · Sep 26, 2012 · Viewed 9.7k times · Source

For a hash of this format:

my $itemHash = {
    tag1 => {
        name => "Item 1",
        order => 1,
        enabled => 1,
    },
    tag2 => {
        name => "Item 2",
        order => 2,
        enabled => 0,
    },
    tag3 => {
        name => "Item 3",
        order => 3,
        enabled => 1,
    },
    ...
}

I have this code that correctly iterates through the hash:

keys %$itemHash; # Resets the iterator
while(my($tag, $item) = each %$itemHash) {
    print "$tag is $item->{'name'}"
}

However, the order that these items are iterated in seems to be pretty random. Is it possible to use the same while format to iterate through them in the order specified by the 'order' key in the hash for each item?

(I know I can sort the keys first and then foreach loop through it. Just looking to see if there is cleaner way to do this.)

Answer

sunil_mlec picture sunil_mlec · Oct 12, 2012

You can do some thing like :

foreach my $key (sort keys %{$itemHash}) {
    print "$key : " . $itemHash->{$key}{name} . "\n";
}