Perl hashes: how to deal with duplicate keys and g

2019-07-13 13:20发布

问题:

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)

回答1:

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.



回答2:

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.



回答3:

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'];