I have pairs like this (Data sorted to %hash format(I have large data))
G1-G2
G2-G3
D1-D2
D3-D2
G3-D3
G2-D3
Perl script
use strict;
use warnings;
use Data::Dumper;
my %hash;
$hash{'G1'}='G2';
$hash{'G2'}='G3';
$hash{'D1'}='D2';
$hash{'D3'}='D2';
$hash{'G3'}='D3';
$hash{'G2'}='D3';
print Dumper \%hash;
Out put
$VAR1 = {
'G1' => 'G2',
'G2' => 'D3',
'D3' => 'D2',
'G3' => 'D3',
'D1' => 'D2'
};
Here missing G2-G3 bcz key hash duplicated
I need to add duplicates (i can use array but have large data system is going slow)
any fast method add pairs and get condition input of possible pairs
If $input=’G2’
Get output G2->(G3,D3,G1)
If $input=’D2’
Get output D2->(D1,D3)
You are correct that there can only be one value for a given hash key. However, that value can be an array, and in your case it sounds like that's what you need. So something like:
my %hash;
push @{$hash{G1}}, 'G2';
push @{$hash{G2}}, 'G3';
...
push @{$hash{G2}}, 'D3';
Which would get you:
$VAR1 = {
'G1' => [
'G2'
],
'G2' => [
'G3',
'D3'
]
};
This method takes advantage of Perl's autovivification, so we don't need to check for the prior existence of a hash key before appending to it.
The best way to support multiple entries in a hash is to use array references as the value. In your case this would mean
$hash{'G1'}=['G2'];
$hash{'G2'}=['G3', 'D3'];
$hash{'D1'}=['D2'];
$hash{'D3'}=['D2'];
$hash{'G3'}=['D3'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With