1

I am trying to read the contents of a file into a hash file contents look line,

A|A1
B|B1
C|C1

the code I have is

use strict;
use warnings;
use Data::Dumper;

my $instAttribFileName="DATABYIDENTIFIER_InstCommonAttrList.config";

open(IFH,$instAttribFileName) or die "cannot open file";
my %attribhash = ();
%attribhash = map {chomp; split /\|/} (<IFH>);
print Dumper %attribhash;

Dumper does not print the hash but reads A,A1 etc into seperate variables.

what am I doing wrong here?

BVAD
  • 75
  • 2
  • 6

2 Answers2

7

According to perldoc perldata:

LISTs do automatic interpolation of sublists. That is, when a LIST is evaluated, each element of the list is evaluated in list context, and the resulting list value is interpolated into LIST just as if each individual element were a member of LIST. Thus arrays and hashes lose their identity in a LIST

So you need to pass the hash by reference to Dumper() or else it will be flattened into a list of separate arguments. For example, if you have:

my %foo = ( a => 'A', b => 'B');
print Dumper %foo;

Output:

$VAR1 = 'b';
$VAR2 = 'B';
$VAR3 = 'a';
$VAR4 = 'A';

but if you pass a reference to %foo instead (by putting a backslash in front):

print Dumper \%foo;

we get:

$VAR1 = {
          'b' => 'B',
          'a' => 'A'
        };

References:

Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174
2

It's always worth reading all of the documentation for the modules you're trying to use. The "BUGS" section in the Data::Dumper manual says:

Due to limitations of Perl subroutine call semantics, you cannot pass an array or hash. Prepend it with a \ to pass its reference instead.

Dave Cross
  • 68,119
  • 3
  • 51
  • 97