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

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

    Hashes are not (necessarily) retrieved in a sorted manner. If you want them sorted, you have to do it yourself:

    use strict;
    use warnings;
    
    my %hash = ("a" => 1, "b" => 2, "c" => 3, "d" => 4);
    
    for my $i (sort keys %hash) {
        print "$i -> $hash{$i}\n";
    }
    

    You retrieve all the keys from a hash by using keys and you then sort them using sort. Yeah, I know, that crazy Larry Wall guy, who would've ever thought of calling them that? :-)

    This outputs:

    a -> 1
    b -> 2
    c -> 3
    d -> 4
    

提交回复
热议问题