从数组的哈希中删除一个键,但我在哈希元素中使用了未初始化的值

时间:2015-04-28 01:57:39

标签: perl

我想知道如何从数组哈希中删除一个键。 鉴于以下文件为简单示例,第四列始终是配对匹配中的第三列,而数据未排序。

....
NS501570        WWW     3009824 3009848 
....
NS501572        WAD     3009848 3009898
....

我想把它折叠成

NS501570        WWW     3009824 3009848 NS501572        WAD     3009848 3009898

我写了以下代码。我选择第三列作为哈希的关键。因此我打印第一个条目的值,第4列是另一个的关键:

use warnings;
use strict;

my $seq;
while(<>){
chomp;
my @line = split;
$seq->{"$line[2]" } = [@line];

}

foreach my $s (keys %{$seq} ) {
### @{ $seq->{$s}}[3] key for the second pair
        print @{ $seq->{$s}}[0],"\t",@{ $seq->{$s}}[1],"\t",@{ $seq->{$s}}[2],"\t",@{ $seq->{$s}}[3],"\t",@{ $seq->{@{ $seq->{$s}}[3]}}[0],"\t",@{ $seq->{@{ $seq->{$s}}[3]}}[1],"\t",@{ $seq->{@{ $seq->{$s}}[3]}}[2],"\t",@{ $seq->{@{ $seq->{$s}}[3]}}[3],"\n";

        delete ${$seq}{@{ $seq->{$s}}[3]};
        }

它有效,但有一个小问题! 我不知道如何删除第二个键(在第二个条目中为3009848),而不会出现以下错误:

NS501570        WWW     3009824 3009848 NS501572        WAD     3009848 3009898
Use of uninitialized value in hash element at find_mate2.pl line 22, <> line 2.
Use of uninitialized value in hash element at find_mate2.pl line 22, <> line 2.
Use of uninitialized value in hash element at find_mate2.pl line 22, <> line 2.
Use of uninitialized value in hash element at find_mate2.pl line 22, <> line 2.
Use of uninitialized value in print at find_mate2.pl line 22, <> line 2.
Use of uninitialized value in print at find_mate2.pl line 22, <> line 2.
Use of uninitialized value in print at find_mate2.pl line 22, <> line 2.
Use of uninitialized value in print at find_mate2.pl line 22, <> line 2.
Use of uninitialized value in print at find_mate2.pl line 22, <> line 2.
Use of uninitialized value in print at find_mate2.pl line 22, <> line 2.
Use of uninitialized value in print at find_mate2.pl line 22, <> line 2.
Use of uninitialized value in print at find_mate2.pl line 22, <> line 2.

Use of uninitialized value in delete at find_mate2.pl line 23, <> line 2.

2 个答案:

答案 0 :(得分:2)

在foreach循环中迭代3009848键之前,您似乎正在删除3009848。您可以尝试一个简单的public void preProcessExport(Object document) { if (document instanceof com.lowagie.text.Document) { // ... } } public void postProcessExport(Object document) { if (document instanceof com.lowagie.text.Document) { // ... } } ,因为您在3009824的交互中删除了$ s == 3009848. next unless defined $seq->{$s};检查永远不会伤害......

答案 1 :(得分:1)

警告是因为你在迭代它们时删除了哈希的元素,这通常是一个坏主意。

Perl警告你,你正在尝试打印不再存在的东西。另外,请注意,除非您对它们进行排序,否则按键会以随机顺序返回。

看看:

How should I delete hash elements while iterating?