简体   繁体   English

如果值相同,则哈希键的串联;如果键相同,则哈希键的串联

[英]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? 有没有一种方法可以在一个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 问候,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"],
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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