What decides the order of keys when I print a Perl hash?

前端 未结 8 1217
挽巷
挽巷 2020-12-03 19:35

activePerl 5.8 based

#!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,         


        
8条回答
  •  执笔经年
    2020-12-03 20:05

    For most practical purposes, the order in which a hash table (not just Perl hash variables, but hash tables in general) can be considered random.

    In reality, depending on the hashing implementation, the order may actually be deterministic. (i.e., If you run the program multiple times putting the same items into the hash table in the same order each time, they'll be stored in the same order each time.) I know that Perl hashes used to have this characteristic, but I'm not sure about current versions. In any case, hash key order is not a reliable source of randomness to use in cases where randomness is desirable.

    Short version, then:

    Don't use a hash if you care about the order (or lack of order). If you want a fixed order, it will be effectively random and if you want a random order, it will be effectively fixed.

提交回复
热议问题