4

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)

user2502386
  • 49
  • 1
  • 7
  • Thanks it works adding multiple value, how get condition input of possible pairs ,if input=G2, if 'print @{$hash{'G2'}};' i will get G2->G3,D3 only, i need all possible eg G2->G3,D3,G1 (G2-G1 has link of value-key pair) eg.2 if input D3, i need output D3->G3,G2 – user2502386 Jun 21 '13 at 02:42

3 Answers3

9

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.

ldx.a.ldy.c
  • 687
  • 4
  • 9
  • Thanks it works adding multiple value, how get condition input of possible pairs ,if input=G2, if 'print @{$hash{'G2'}};' i will get G2->G3,D3 only, i need all possible eg G2->G3,D3,G1 (G2-G1 has link of value-key pair) – user2502386 Jun 21 '13 at 02:51
1

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'];
levengli
  • 1,091
  • 7
  • 18
1

I think building up little arrays as suggested in both the answers of levengli and ldx.a.ldy.c is your best option.

Alternatively, you could just use Hash::MultiValue.

innaM
  • 47,505
  • 4
  • 67
  • 87