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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…