Perl中,数组的哈希:添加和删除键,再配以一个数组,都在一个while循环 [英] Perl, A hash of arrays: adding and removing keys, adding to an array, all in a while loop

查看:254
本文介绍了Perl中,数组的哈希:添加和删除键,再配以一个数组,都在一个while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有它应该包含哪些链接到自己的阵列某些键的哈希。为了更具体,散列键是质量值和阵列序列的名称。如果已经有该质量阵列,我想序列名称添加到链接到有问题的质量的阵列。如果没有一个,我想创建一个并添加顺序姓名。所有这一切都在一个while循环逐个完成,通过所有的序列去。

I have a hash which should contain certain keys which are linked to their own arrays. To be more specific, the hash keys are quality values and the arrays are sequence names. If there already is an array for that quality, I'd want to add the sequence name to the array that is linked to the quality in question. If there isn't one, I want to create one and add the sequence name to it. All this is done in a while loop, going through all the sequences one by one.

我一直试图做这样的事情在<一href=\"http://stackoverflow.com/questions/12535408/perl-how-do-i-retrieve-an-array-from-a-hash-of-arrays\">Perl我如何检索阵列的散列数组?,但我似乎无法得到它的权利。

I've tried to do things like in Perl How do I retrieve an array from a hash of arrays? but I can't seem to get it right.

我只想找到这些错误信息:
标量值@ {哈希{$ Q}在asdasd.pl线69更好地写成$ {哈希{$ Q}。
全球符号@q要求明确包名asdasd.pl线58。
和其他一些人也。

I just get these error messages: Scalar value @{hash{$q} better written as ${hash{$q} at asdasd.pl line 69. Global symbol "@q" requires explicit package name asdasd.pl line 58. And some others, too.

下面是什么,我已经试过一个例子:

Here is an example of what I've tried:

my %hash;
while (reading the sequences) {
    my $q = "the value the sequence has";
    my $seq = "the name of the sequence";

    if (exists $hash{$q}) {
        push (@{$hash{$q}}, $seq);
    } else {
        $hash{$q} = \@q;
        $hash{$q} = [$seq];
        next;
    }
}

这显然不应该是一个非常复杂的问题,但我是新来的Perl和这样的问题感到困难。我已经从不同的地方用Google搜索这一点,但似乎有东西,我只是不知道,这可能是真的很明显了。

This obviously shouldn't be a very complicated problem but I'm new to perl and this kind of a problem feels difficult. I've googled this from various places but there seems to be something I just don't realize, and it might be really obvious, too.

推荐答案

您可以用什么perl的通话自动激活的使这个很容易的。您code并不需要一个中央if语句。你可以熬它归结为:

You can use what perl calls autovivification to make this quite easy. Your code doesn't need that central if-statement. You can boil it down to:

    push @{ $hash{$q} }, $seq;

如果特定的关键还不在哈希存在,perl的将autoviv它,因为它可以推断​​出你在这里想要一个数组引用。

If the particular key doesn't yet exist in the hash, perl will autoviv it, since it can infer that you wanted an array reference here.

您可以通过谷歌搜索就找到进一步的自动激活资源。这是一个独特的足够字,绝大多数的命中显得重要。 : - )

You can find further resources on autovivification by Googling it. It's a unique enough word that the vast majority of the hits seem relevant. :-)

这篇关于Perl中,数组的哈希:添加和删除键,再配以一个数组,都在一个while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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