Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何将数组添加到哈希值_Arrays_Perl_Hash_Key Value_Post Processing - Fatal编程技术网

Arrays 如何将数组添加到哈希值

Arrays 如何将数组添加到哈希值,arrays,perl,hash,key-value,post-processing,Arrays,Perl,Hash,Key Value,Post Processing,我有一些值和生成这些值的根。 例如,在值根格式中 100-0 200-1 300-2 100-2 400-1 300-3 100-3 现在,我需要以以下格式在Perl中创建数组散列。 钥匙是100200300400;下面给出了每个键对应的值(与值的根相同) 100-0,2,3 200-1 300-2,3 400-1 我给出了我编写的代码,以实现同样的目的。但是每个键的值都是零 下面代码的一部分在一个循环中,它在$root_num的每次迭代中提供不同的根编号,根据上面的示例,它们是100、200、

我有一些值和生成这些值的根。 例如,在值根格式中

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

现在,我需要以以下格式在Perl中创建数组散列。 钥匙是100200300400;下面给出了每个键对应的值(与值的根相同)

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-23
200-
300-3
400-

另外,我如何对散列进行后期处理,以使根不会在不同的键值中重复,并且根应该位于最大数字键中,在这种情况下,散列键值将紧随其后

100-0
200-
300-23

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