![](/img/trans.png)
[英]How to turn an array into the keys of a Hash and another array into the values of the same hash?
[英]Concatenation of Hash keys if the values are same and Concatenation of Hash values if the keys are same
有沒有一種方法可以在一個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;
}
}
請指教。
問候,Divesh
如果要建立雙向關系,則只需要兩個散列:
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"],
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.