Reputation: 1949
I have a hash of hashes where, at the last level, I want each value to be appended - not updated - if that value already exists. What would be the best way to do this? I was thinking about making the values as lists, but this is probably not the most efficient way...
Here's where I got so far:
#!/usr/local/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $dir='D:\';
open my $data,"<","$dir\\file.txt";
my (@selecteddata,@array,%hash);
while (<$data>) {
chomp $_;
my @line= split "\t";
$hash{$line[1]}{$line[2]}=$line[0];
warn Dumper \%hash;
}
close $data;
Note, this code updates the values at last level with value $line[0]
, but if the key $line[4]
already exists (meaning, it already has a previous value $line[0]
) I want this value to be appended and not updated.
So, ideally, for the following (tab sepparated) list:
a1 b1 c1
a2 b2 c2
a3 b3 c3
a4 b4 c4
a5 b4 c4
The hash would look something like this - I don't know exactly how the grouping of a4
and a5
should look like, so as long as they are grouped it should be ok:
{
'b1' => {'c1' => 'a1'},
'b2' => {'c2' => 'a2'},
'b3' => {'c3' => 'a3'},
'b4' => {'c4' => 'a4, a5'}
}
Upvotes: 0
Views: 3941
Reputation: 50637
You can append your string,
$_ = defined($_) ? "$_, $line[0]" : $line[0]
for $hash{$line[1]}{$line[2]};
or use array which is better suited for storing list of elements,
push @{ $hash{$line[1]}{$line[2]} }, $line[0];
Upvotes: 4