I want to build several hashes using the same keys and for the keys to have the same order when I print them. So, in the example below, the keys of $hash1
and $hash2
should always have the same order, but there should be no need to keep that order when creating the hash.
use Data::Dumper;
my $hash1 = {
keyc => 2,
key1 => 1,
keya => 3,
keyb => 4,
};
my $hash2 = {
keyc => 2,
key1 => 1,
keya => 3,
keyb => 4,
};
print Dumper $hash1, $hash2;
But the output is as follows:
$VAR1 = {
'key1' => 1,
'keyc' => 2,
'keyb' => 4,
'keya' => 3
};
$VAR2 = {
'keyb' => 4,
'keya' => 3,
'keyc' => 2,
'key1' => 1
};
i.e the hashes have a different and unexpected order. What's wrong with my perl?
My perl version is:
This is perl 5, version 18, subversion 2 (v5.18.2) built for darwin-thread-multi-2level
(with 2 registered patches, see perl -V for more detail)
Notice: I know that keys of perl hash is unsorted order. I want they have the same order, but there should be no need to have the sorted order. I hope that I can get the same print output if I run the code again.
Following advice from answers, I set two environment variables:
PERL_HASH_SEED=0x00 PERL_PERTURB_KEYS=0
Then I can get the same output when I run the code repeatedly.
PERL_HASH_SEED
and usePERL_PERTURB_KEYS=0
If you want the keys to stay in their insertion order (ordered but not sorted). This was not clear in your question. If you are serious about maintaining the order in the application (rather than relying on an environment variable) you would be better off tieing the hash with one of the CPAN modules that were mentioned.