ezionice
ezionice

Reputation: 9

The sort order is not applied

I need order an hash in perl. I push value in a hash. Then i need to order it. The problem is that is not ordered. This is my code:

my %hash_section;
for my $y (0..$#xml) {
    if ( $xml[$y] =~m/<sezione numero="(.*?)">(.*?)<\/sezione>/i) { 
        push @{$hash_section{$xml[$y]}}, $1;            
    }
}
foreach my $i(sort {$a <=> $b} values %hash_section) {
    say Dumper(\%hash_section);
}

Can you help me?

Upvotes: 0

Views: 72

Answers (1)

ikegami
ikegami

Reputation: 386501

Hash are inherently unordered.

You are getting the values of the elements of the hash and sorting those. Then you loop over the sorted values. But you don't actually use them ($i). Instead, you repeatedly dump the hash.

Maybe you want

for my $key (
   sort { $hash_section{ $a } <=> $hash_section{ $b } }
      keys( %hash_section )
) {
   say "$key: $hash_section{ $key }";
}

This gets the keys of the elements of the hash and sorts them by their associated value. Then, it loops over the sorted keys. For each sorted key, it prints the key and the associated value.

Upvotes: 4

Related Questions