in reply to Sort Hash of hashes

Hashes are unsorted by definition. The most common case is that you just want them sorted on output, in which case see for example How do I sort a hash (optionally by value instead of key)?, as well as Data::Dumper's Sortkeys option. If you really, really need to store them in a sorted order, see How can I always keep my hash sorted? (although sometimes people will solve this by simply keeping an array with the names of the keys in a sorted order, and use that to iterate over the hash)

Replies are listed 'Best First'.
Re^2: Sort Hash of hashes
by lobs (Acolyte) on Mar 22, 2016 at 22:02 UTC
    I don't need to display the hash at all. Later on in the program I am storing just the key within an array,
    @tags = keys %{ $bigrams{$element}}
    Is there a way to sort the key by there value.
      Yes! here is a short program to illustrate the idea:
      #/usr/bin/perl use warnings; use strict; my %hash = (a => 4, b => 6, c => 2); my @sorted_keys = sort keys %hash; print "@sorted_keys\n"; my @sort_by_value = sort{my $A = $hash{$a}; my $B = $hash{$b}; $A <=> $B ## or cmp for strings }keys %hash; print "@sort_by_value\n"; __END__ Prints: a b c # simple key sort c a b # keys sorted by value of keys
      The sort{} takes input from the right and sends the same output to the left except in a different order. What goes inside the {} are the "rules" for how to sort the input. $a and $b are special Perl variables that are assigned various values as needed to sort the input. The "return value" of the sort {} should be <0,0,>0 just like the cmp statement does for strings or the "spaceship" operator, <=> does for numbers.