簡體   English   中英

如何將數組添加到哈希值

[英]How to add array to hash values

我有一些價值觀和產生這些價值觀的根源。 例如在 value-root 格式中。

100-0
200-1
300-2
100-2
400-1
300-3
100-3

現在我需要在 Perl 中按以下格式創建數組的哈希。 鍵為 100、200、300、400; 下面給出了每個鍵對應的值(與值的根相同)。

100-0,2,3
200-1
300-2,3
400-1

我正在提供我為實現相同目的而編寫的代碼。 但是每個鍵的值都為零。

下面部分代碼在一個循環中,它在 $root_num 中的每次迭代中提供不同的根數,根據上面的例子,它們是 100、200、300、400。

每次迭代中的根數為 100、200、300 和 400。

my %freq_and_root;
my @HFarray = ();
my @new_array = ();

if(exists $freq_and_root{$freq_value}) 
{
    @HFarray = @{ $freq_and_root{$freq_value} };
    $new_array[0] = $root_num;
    push(@HFarray,$new_array[0]);
    $freq_and_root{$freq_value} = [@HFarray] ;
} else {  
    $new_array1[0] = $root_num;
    $freq_and_root{$freq_value} = $new_array1[0];
}  

最后在循環之后我打印哈希如下:

foreach ( keys %freq_and_root) {  
    print "$_ => @{$freq_and_root{$_}}\n";
}  

以下是輸出,我缺少每個鍵值中的第一項
100-2 3
200-
300-3
400-

另外,我如何對哈希進行后處理,以便根不會在不同的鍵值中重復,並且根應該在最高數字鍵中,在這種情況下將跟隨哈希鍵值

100-0
200-
300-2 3
400-1

看看下面的代碼是否滿足你的要求

use strict;
use warnings;
use feature 'say';

my %data;

while(<DATA>) {                          # walk through data
    chomp;                               # snip eol
    my($root,$value) = split '-';        # split into root and value
    push @{$data{$root}}, $value;        # fill 'data' hash with data
}

foreach my $root(sort keys %data) {      # sort roots
    say "$root - " . join ',', @{$data{$root}};  # output root and values
}

__DATA__
100-0
200-1
300-2
100-2
400-1
300-3
100-3

輸出

100 - 0,2,3
200 - 1
300 - 2,3
400 - 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM