【问题标题】:Concatenation of Hash keys if the values are same and Concatenation of Hash values if the keys are same如果值相同,则连接哈希键,如果键相同,则连接哈希值
【发布时间】:2014-11-21 01:31:03
【问题描述】:

有没有办法在一个 HOA 中结合哈希的键和值?假设我有一个示例输入,例如

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

在上面的代码中,哈希值不同但它们的键相同,而在下面的代码中,值相同但键不同。

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

以下代码可以处理值的合并,但不能处理键的合并。

 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;
        }
    }

请指教。

问候, 潜水

【问题讨论】:

  • 您不能有多个具有相同名称的哈希键。您的代码已经“合并了键”,因为如果键已经存在,您将使用它。
  • 我能够通过流程所需的一些简单逻辑来解决这个问题。谢谢你的建议。

标签: arrays perl hash


【解决方案1】:

如果你想要一个双向关系,那么你只需要两个哈希:

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

输出:

{
  "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"],
}

【讨论】:

    猜你喜欢
    • 2013-02-24
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    相关资源
    最近更新 更多