The order is jumbled because Perl keeps the key-value pairs in an order that’s conven-
ient for Perl so that it can look up any item quickly.
Elements of a hash are printed out in their internal order, which can not be relied upon and will change as elements are added and removed. If you need all of the elements of a hash in some sort of order, sort the keys, and use that list to index the hash.
If you are looking for a structure that holds its elements in order, either use an array, or use one of the ordered hash’s on CPAN.
the only ordering you can rely upon from a list context hash expansion is that key => value pairs will be together.
use the keys function to get a list of the keys. They will most likely be in the same order as they’re stored in the hash itself, although there’s no guarantee. If the order matters, then you either shouldn’t be using a hash in the first place, or you should use the keys function to get a list, put the items in the desired order, and then loop through that list, accessing each corresponding hash item.
#!C:\Perl\bin\perl.exe
use strict;
use warnings;
# declare a new hash
my %some_hash;
%some_hash = ("foo", 35, "bar", 12.4, 2.5, "hello",
"wilma", 1.72e30, "betty", "bye");
my @any_array;
@any_array = %some_hash;
print %some_hash;
print "\n";
print "\n";
print @any_array;
print "\n";
print "\n";
my @keys;
@keys = keys %some_hash;
for my $k (sort @keys)
{
print $k, $some_hash{$k};
}
print "\n";
print "\n";
print map {$_, $some_hash{$_}} sort keys %some_hash;
Output
D:\learning\perl>test.pl bettybyebar12.4wilma1.72e+030foo352.5hello bettybyebar12.4wilma1.72e+030foo352.5hello 2.5hellobar12.4bettybyefoo35wilma1.72e+030 2.5hellobar12.4bettybyefoo35wilma1.72e+030 D:\learning\perl>
-from StackOverflow.com