简体   繁体   中英

how to perform merging of keys for common values in hash of hash in perl

I am working on a below hash of hashes in perl, wherein i have some values in inner hash that are same for different key timestamps. Is there any way to merge the timestamp keys for similar values?

'Test Responder Data String' => { 
                        '2018-01-26' => 'zzz00175002802;newData1',
                        '2018-01-20' => 'xxy00171329968;data1',
                        '2018-01-27' => 'xxy00171329968;data1',
                        '2018-01-28' => 'xxy00171329968;data1'
                        '2018-01-04' => 'www00171510082;ResponderData',
                        '2018-01-17' => 'rrr00175002256;try data',
                        '2018-01-05' => 'aaa00175033226;response try', 
                        '2018-01-08' => 'aaa00175033226;response try'
                       }

Expected Result:

'Test Responder Data String' => { 
                        '2018-01-26'                       => 'zzz00175002802;newData1',
                        '2018-01-20,2018-01-27,2018-01-28' => 'xxy00171329968;data1',
                        '2018-01-04'                       => 'www00171510082;ResponderData',
                        '2018-01-17'                       => 'rrr00175002256;try data',
                        '2018-01-05,2018-01-08'            => 'aaa00175033226;response try'                                                                                 
                       }
my %h=(
    '2018-01-26' => 'zzz00175002802;newData1',
    '2018-01-20' => 'xxy00171329968;data1',
    '2018-01-27' => 'xxy00171329968;data1',
    '2018-01-28' => 'xxy00171329968;data1',
    '2018-01-04' => 'www00171510082;ResponderData',
    '2018-01-17' => 'rrr00175002256;try data',
    '2018-01-05' => 'aaa00175033226;response try', 
    '2018-01-08' => 'aaa00175033226;response try'
);
my %t;
push @{ $t{ $h{$_} } }, $_ for keys %h;

my %result = map { join(",", @{$t{$_}}) => $_ } keys %t;

use Data::Dumper; print Dumper \%result;

output

$VAR1 = {
      '2018-01-17' => 'rrr00175002256;try data',
      '2018-01-05,2018-01-08' => 'aaa00175033226;response try',
      '2018-01-26' => 'zzz00175002802;newData1',
      '2018-01-04' => 'www00171510082;ResponderData',
      '2018-01-27,2018-01-20,2018-01-28' => 'xxy00171329968;data1'
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM