Perl hashes: how to deal with duplicate keys and g

2019-07-13 13:14发布

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)

3条回答
The star\"
2楼-- · 2019-07-13 13:41

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楼-- · 2019-07-13 13:45

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.

查看更多
成全新的幸福
4楼-- · 2019-07-13 13:52

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'];
查看更多
登录 后发表回答