简体   繁体   中英

Concatenation of Hash keys if the values are same and Concatenation of Hash values if the keys are same

Is there a way to combine both keys and values of a hash in one HOA? Let's say i've a sample input like

#NewName              OldName
Axc.Sx2.1_Axc.Wx2.1  1BDER
Axc.Sx2.1_Axc.Wx2.1  1ADER

In the above code values of the hash are different but their keys are same whereas in the below code values are same but keys are different.

Axc.Sx2.1_Axc.Wx2.1  1BDER
Axc.Sx2.1_Axc.Wx2.1  1BDER
Axc.Sx2.1            1BDER

Following code can handle the merging of values, but can't handle the keys merging.

 while (<$mapF>) {
        chomp $_;
        next if /^\s*(#.*)?$/;
        next if /^\s+.*$/;
        ##latestRuleName OldRuleName
        if ( $_ =~ /(\S+)\s+(\S+)/gi ) {
            # create list and append $2
           push @{ $mapHash{$1} }, $2;
        }
    }

Please advise.

Regards, Divesh

If you want a two-way relationship, then you simply need two hashes:

use strict;
use warnings;

my %new2old;
my %old2new;

while (<DATA>) {
    my ( $new, $old ) = split ' ';
    push @{ $new2old{$new} }, $old;
    push @{ $old2new{$old} }, $new;
}

use Data::Dump;

dd \%new2old;
dd \%old2new;

__DATA__
Axc.Sx2.1_Axc.Wx2.1  1BDER
Axc.Sx2.1_Axc.Wx2.1  1ADER
Axc.Sx2.1            1BDER

Outputs:

{
  "Axc.Sx2.1" => ["1BDER"],
  "Axc.Sx2.1_Axc.Wx2.1" => ["1BDER", "1ADER"],
}
{
  "1ADER" => ["Axc.Sx2.1_Axc.Wx2.1"],
  "1BDER" => ["Axc.Sx2.1_Axc.Wx2.1", "Axc.Sx2.1"],
}

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