Perl hash giving undef values

1.1k views Asked by At

If was trying to write a piece of code using perl hash. There are no undefined values or new lines in __DATA__(tried giving same input from file also). But while printing using data dumper or the traditional way I am getting a '' as key and undef as its value. Why is this happening ? Am I missing something obvious ?

Program:

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

There are 1 answers

3
ikegami On BEST ANSWER

Always use use warnings;!

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

gives

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.

You didn't provide a value for the value element, so undef is used after issuing a warning.

Keys are strings and the stringification of undef is the empty string, though doing so issues a warning.

You want:

my %i_hash;
my %p_hash;