Sort a hash by value when it has many keys

I believe this is how you usually sort the hash by value:

foreach my $key (sort { $hash{$a} <=> $hash{$b} } (keys %hash) ) {
    print "$key=>$hash{$key}";
}

This will output the smallest values.

Now, if I have a hash like this:

$hash{$somekey}{$somekey2}{$thirdkey}

How can I sort by values ​​and get all keys?

+5
source share
4 answers

I would just create a new hash:

my %new;
for my $k1 (keys %hash) {
  for my $k2 (keys %{$hash{$k1}}) {
    for my $k3 (keys %{$hash{$k1}{$k2}}) {
      $new{$k1,$k2,$k3} = $hash{$k1}{$k2}{$k3};
    }
  }
}

my @ordered = sort { $new{$a} <=> $new{$b} } keys %new;
for my $k (@ordered) {
  my @keys = split($;, $k);
  print "key: @k      - value: $new{$k}\n";
}
+3
source

Here is a way to do this using Deep :: Hash :: Utils .

use Deep::Hash::Utils qw(slurp);

my %h = (
    A => {
        Aa => { Aaa => 4, Aab => 5 },
        Ab => { Aba => 1 },
        Ac => { Aca => 2, Acb => 9, Acc => 0 },
    },
    B => {
        Ba => { Baa => 44, Bab => -55 },
        Bc => { Bca => 22, Bcb => 99, Bcc => 100 },
    },
);

my @all_keys_and_vals = slurp \%h;
print "@$_\n" for sort { $a->[-1] <=> $b->[-1] } @all_keys_and_vals;

Conclusion:

B Ba Bab -55
A Ac Acc 0
A Ab Aba 1
A Ac Aca 2
A Aa Aaa 4
A Aa Aab 5
A Ac Acb 9
B Bc Bca 22
B Ba Baa 44
B Bc Bcb 99
B Bc Bcc 100
+1
source

- , -. .

, , .

. (: my @Keys = ('Value', 'Value2');)

, , .

my $list_ref;
my $pointer;

my %list = (
   Value => {
      Value2 => {
         A => '1',
         C => '3',
         B => '2',
      },
   },
);

$list_ref = \%list;
$pointer = $list_ref->{Value}->{Value2};

foreach my $key (sort { $pointer->{$a} <=> $pointer->{$b} } (keys %{$pointer})) {
   print "Key: $key\n";
}
+1

:

sub flatten_hash {
  my ($hash, $path) = @_;
  $path = [] unless defined $path;

  my @ret;

  while (my ($key, $value) = each %$hash) {
    if (ref $value eq 'HASH') {
      push @ret, flatten_hash($value, [ @$path, $key ]);
    } else {
      push @ret, [ [ @$path, $key ], $value ];
    }
  }

  return @ret;
}

{
    roman => {
        i => 1,
        ii => 2,
        iii => 3,
    },
    english => {
        one => 1,
        two => 2,
        three => 3,
    },
}

,

(
    [ ['roman','i'], 1 ],
    [ ['roman', 'ii'], 2 ],
    [ ['roman', 'iii'], 3 ],
    [ ['english', 'one'], 1 ],
    [ ['english', 'two'], 2 ],
    [ ['english', 'three'], 3 ]
)

, , . , { $a->[1] <=> $b->[1] } , @{ $entry->[0] } . . , , hashrefs , .

+1

All Articles