【问题标题】:How to add array to hash values如何将数组添加到哈希值
【发布时间】:2020-06-08 19:46:30
【问题描述】:

我有一些价值观和产生这些价值观的根源。 例如在值根格式中。

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

【问题讨论】:

标签: arrays perl hash key-value post-processing


【解决方案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

【讨论】:

    猜你喜欢
    • 2012-09-03
    • 2011-07-26
    • 2018-01-28
    • 2011-07-28
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多