http://qs1969.pair.com?node_id=1167789


in reply to setting PERL_PERTURB_KEYS & PERL_HASH_SEED in a perl file

Hi gravid,

As far as I can tell from a glance at the source, Perl only checks those environment variables once on startup (the function Perl_get_hash_seed in util.c sets the variables PL_hash_rand_bits_enabled and PL_hash_rand_bits). It might be possible to change the values at runtime from XS code, but that's not my area of expertise.

But I think it's important to point out that hash ordering has always been random, even though older Perls used to return hash keys with some consistency to the ordering, leading to code sometimes relying on this fact. But at least since v5.18.0 that has changed, see Hash overhaul. The bottom line is, one shouldn't rely on the order hash keys are returned in, in any version of Perl.

I find the easiest solution is usually something like for my $key (sort keys %hash) ..., or in some cases modules like Tie::IxHash can help. See also How do I sort a hash (optionally by value instead of key)? This might be the "better way" to fix your code than to rely on Perl's hash ordering.

Hope this helps,
-- Hauke D