fork download
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use Data::Dumper qw(Dumper);
  7.  
  8. sub join_by_value {
  9. my ($hash) = @_;
  10.  
  11. my %result = ();
  12. while (my ($key, $value) = each %$hash) {
  13. push @{$result{$value}}, $key;
  14. }
  15.  
  16. return %result;
  17. }
  18.  
  19. my %h = (
  20. 'qwe' => 'q1',
  21. 'asd' => 'q2',
  22. 'zxc' => 'q3',
  23. 'vbn' => 'q2',
  24. 'rty' => 'q1',
  25. 'fgh' => 'q3'
  26. );
  27.  
  28. my %joined = join_by_value(\%h);
  29. print Dumper(\%joined);
  30.  
Success #stdin #stdout 0.02s 5984KB
stdin
Standard input is empty
stdout
$VAR1 = {
          'q2' => [
                    'vbn',
                    'asd'
                  ],
          'q1' => [
                    'rty',
                    'qwe'
                  ],
          'q3' => [
                    'zxc',
                    'fgh'
                  ]
        };