简体   繁体   English

如何将数组添加到哈希值

[英]How to add array to hash values

I have some values and the roots that generate these values.我有一些价值观和产生这些价值观的根源。 For example in the value-root format.例如在 value-root 格式中。

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

Now I need to create a Hash of arrays in Perl in the following format.现在我需要在 Perl 中按以下格式创建数组的哈希。 keys are 100, 200, 300, 400;键为 100、200、300、400; and the values corresponding to each key are given below (same as the roots of the values).下面给出了每个键对应的值(与值的根相同)。

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

I am giving the code I have written to achieve the same.我正在提供我为实现相同目的而编写的代码。 But the value for each key is coming as nil.但是每个键的值都为零。

Below part of the code is inside a loop in which it supplies different root numbers in each iteration in $root_num, As per the above example, they are 100, 200, 300, 400.下面部分代码在一个循环中,它在 $root_num 中的每次迭代中提供不同的根数,根据上面的例子,它们是 100、200、300、400。

Root Number is 100, 200, 300 and 400 in each iteration.每次迭代中的根数为 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];
}  

Finally after the loop I am printing the hash as follows:最后在循环之后我打印哈希如下:

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

Following is the output, I am missing the first item in every key-value以下是输出,我缺少每个键值中的第一项
100-2 3 100-2 3
200- 200-
300-3 300-3
400- 400-

Also how can I post-process the hash so that roots are not repeated in the different key values and root should be there in the highest number key, Hash key values will be following in that case另外,我如何对哈希进行后处理,以便根不会在不同的键值中重复,并且根应该在最高数字键中,在这种情况下将跟随哈希键值

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

See if following code satisfies your requirements看看下面的代码是否满足你的要求

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

Output输出

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