Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem accessing hash imported from CSV in Perl

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

$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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading