Home > Back-end >  Problem accessing hash imported from CSV in Perl
Problem accessing hash imported from CSV in Perl

Time:05-19

I am working with the Text::CSV library of Perl to import data from a CSV file, using the functional interface (https://metacpan.org/pod/Text::CSV#SYNOPSIS). The data is stored in an array of hashes, and the problem is that when the script tries to access those elements/keys, they are uninitialized (or undefined).

Using the library Dumper, it is possible to see that the array and the hashes are not empty, in fact, they are correctly filled with the data of the CSV file.

With this small piece of code, I get the following output:

my $array = csv(
    in => $csv_file,
    headers => 'auto');
foreach my $mem (@{$array}) {
    print Dumper $mem;
    foreach (keys $mem) {
        print $mem{$_};
    }
}

Last part of the output:

    $VAR1 = {
          'Column' => '16',
          'Width' => '13',
          'Type' => 'RAM',
          'Depth' => '4096'
        };
Use of uninitialized value in print at ** line 81.
Use of uninitialized value in print at ** line 81.
Use of uninitialized value in print at ** line 81.
Use of uninitialized value in print at ** line 81.

This happens with all the elements of the array. Is this problem related to the encoding, or I am just simply accessing the elements in a incorrect way?

CodePudding user response:

$mem is a reference to a hash, but you keep trying to use it directly as a hash. Change your code to:

foreach (keys %$mem) {
    print $mem->{$_};
}

There is a slight complication in that in some versions of perl, 'keys $mem' was allowed directly as an experimental feature, which later got removed. In any case, adding

use warnings;
use strict;

would likely have given you some helpful clues as to what was happening.

CodePudding user response:

When I run your code on my version of Perl (5.24), I get this error:

Experimental keys on scalar is now forbidden at ... line ...

This points to the line:

foreach (keys $mem) {

You should dereference the hash ref:

use warnings;
use strict;
use Data::Dumper;
use Text::CSV qw( csv );
 
my $csv_file="data.csv";
my $array = csv(
    in => $csv_file,
    headers => 'auto');

foreach my $mem (@{$array}) {
    print Dumper($mem);
    foreach (keys %{ $mem }) {
        print $mem->{$_}, "\n";
    }
}
  • Related