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

前端 未结 8 1171
挽巷
挽巷 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.

    0 讨论(0)
  • 2020-12-03 20:17

    And if you are crazy and have no duplicate values in your hash, and you need the values sorted, you can call reverse on it.

    my %hash = ("a" => 1, "b" => 2, "c" => 3, "d" => 4);
    my %reverse_hash = reverse %hash;
    
    print $_ for sort keys %reverse_hash;
    

    Caveat is the unique values part, duplicates will be overwritten and only one value will get in.

    0 讨论(0)
提交回复
热议问题