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

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

提交回复
热议问题