The order of the key/value pairs in the list you use to initialize the hash variable is not preserved; by the time the hash variable is populated, that ordering is long gone.
To preserve the order in which the keys were originally added to the hash - which includes the order of any list used to initialize it - you can use the CPAN module Hash::Ordered
.
It has a tie
interface, so you can use a Hash::Ordered
object as if it were a plain hash. Note that you don't need to quote keys on the left side of =>
if they're simple words:
use Hash::Ordered;
tie my %hash, Hash::Ordered => (
ev2 => 'aaaa',
ev1 => 'bbbb'
);
while (my ($key, $value) = each %hash) {
print "$key - $value\n";
}
Output:
ev2 - aaaa
ev1 - bbbb
You could also do the loop as in your original code, just without the sort
:
for my $key (keys %hash) {
print "$key - $hash{$key}\n";
}
But using each
saves a hash lookup for each item and returns them in the same order as keys
.
@duskwuff suggested Hash::Ordered
first; I just supplied some sample code. @ikegami suggested the older module Tie::IxHash
. Both work for this purpose, and neither comes standard with Perl; you need to install them from the CPAN (e.g. with the cpan
or cpanm
commands).