Perl哈希:如何处理重复的密钥并获得可能的对 [英] Perl hashes: how to deal with duplicate keys and get possible pair

查看:154
本文介绍了Perl哈希:如何处理重复的密钥并获得可能的对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的对(数据按%hash格式排序(我有大数据))
G1-G2
G2-G3
D1-D2
D3-D2
G3-D3
G2-D3

Perl脚本

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;

输出
$ VAR1 = { 'G1'=>'G2', 'G2'=>'D3', 'D3'=>'D2', 'G3'=>'D3', 'D1'=>'D2' };

此处缺少G2-G3 bcz密钥哈希重复
我需要添加重复项(我可以使用数组,但大型数据系统运行缓慢)

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)

任何快速方法添加对并获取可能的对的条件输入

如果$ input ='G2'
获取输出G2->(G3,D3,G1)

如果$ input ='D2'
获取输出D2->(D1,D3)

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

哪位可以帮助您:

$VAR1 = {
          'G1' => [
                    'G2'
                  ],
          'G2' => [
                    'G3',
                    'D3'
                  ]
        };

此方法利用了Perl的自动生存,因此我们不需要检查哈希键在附加到哈希键之前已存在.

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.

这篇关于Perl哈希:如何处理重复的密钥并获得可能的对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆