Perl哈希给出undef值

时间:2013-12-26 04:24:18

标签: perl perl-hash

如果尝试使用perl hash编写一段代码。 __DATA__中没有未定义的值或新行(尝试从文件中提供相同的输入)。但是在使用数据转储器或传统方式打印时,我得到''作为键,undef作为其值。为什么会这样?我错过了一些明显的东西吗?

程序:

use strict;
use Data::Dumper;

my %i_hash = undef;
my %p_hash = undef;

while (<DATA>) {
    chomp;
    my @line = split(/\h+/);
    $i_hash{ $line[0] } = $line[1];    # Interactions Hash
    $p_hash{ $line[0] } = $line[2];    # PMIDs Hash

}
print Dumper( \%i_hash, \%p_hash );

__DATA__
AAA     BBB     PMID_1
BBB     AAA     PMID_2
CCC     AAA     PMID_3
DDD     CCC     PMID_4
EEE     FFF     PMID_1
FFF     GGG     PMID_6

OutPut:

$VAR1 = {
      '' => undef,
      'FFF' => 'GGG',
      'CCC' => 'AAA',
      'BBB' => 'AAA',
      'EEE' => 'FFF',
      'DDD' => 'CCC',
      'AAA' => 'BBB'
    };
$VAR2 = {
      '' => undef,
      'FFF' => 'PMID_6',
      'CCC' => 'PMID_3',
      'BBB' => 'PMID_2',
      'EEE' => 'PMID_1',
      'DDD' => 'PMID_4',
      'AAA' => 'PMID_1'
    };

1 个答案:

答案 0 :(得分:3)

始终使用use warnings;

my %i_hash = undef;
my %p_hash = undef;

给出

Odd number of elements in hash assignment at a.pl line 6.
Use of uninitialized value in list assignment at a.pl line 6.
Odd number of elements in hash assignment at a.pl line 7.
Use of uninitialized value in list assignment at a.pl line 7.

您没有为value元素提供值,因此在发出警告后会使用undef

键是字符串,undef的字符串化是空字符串,但这样做会发出警告。

你想:

my %i_hash;
my %p_hash;