简体   繁体   中英

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.

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

Now I need to create a Hash of arrays in Perl in the following format. keys are 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
200-1
300-2,3
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 Number is 100, 200, 300 and 400 in each iteration.

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
200-
300-3
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
200-
300-2 3
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM