我有一些值和生成这些值的根。例如在值根格式中。
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
我给出了我写的代码,以实现同样的目的。但是每个键的值都是nil。
下面的代码在一个循环中,它在$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";
} 以下是输出,我遗漏了每个key-value中的第一项
100-2 3
200-
300-3
400-
100-0
200-
300-2 3
400-1
发布于 2020-02-25 16:51:09
看看下面的代码是否满足您的需求
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 - 1https://stackoverflow.com/questions/60388467
复制相似问题