Advertisement
cwchen

Sort by value demo

Dec 3rd, 2016
369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.58 KB | None | 0 0
  1. my %hash = (
  2.             'L3D0' => '3 0',
  3.             'L3D7' => '3 7',
  4.             'L13D0' => '13 0',
  5.             'L13D1' => '13 1',
  6.             'L13D7' => '13 7',
  7.     );
  8.  
  9. my %hash_1;
  10. while (my ($k, $v) = each(%hash)) {
  11.     my @a = sort { $a <=> $b } split /[ ]/, $v;
  12.     $hash_1{$k} = \@a;
  13. }
  14.  
  15. sub sort_by_value {
  16.     my ($k_a, $k_b) = @_;
  17.     my @a = @{$hash_1{$k_a}};
  18.     my @b = @{$hash_1{$k_b}};
  19.     return (($a[0] <=> $b[0]) or ($a[1] <=> $b[1]));
  20. }
  21.  
  22. my @sorted_keys = sort { sort_by_value $a, $b } keys %hash_1;
  23.  
  24. for my $k (@sorted_keys) {
  25.     print $k, "=>", "@{$hash_1{$k}}", "\n";
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement