Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get desired hash for CSV format in perl

I have exported most common emp table as CSV. I would like to take each column name as hash key and store the values in an array.

Below is the code

 use Data::Dumper;
    open($fh,"<EMP.csv");
    %hash = ();

    local $/= "\n";

    while(<$fh>){

         @columnNames = split(/,/,$_) if $. ==1;     
         @columnValues = split(/,/,$_);  
          push @{hash->{@columnNames}} ,@columnValues;       
    }

    print Dumper(\%hash);

when I try to print the hash I am getting this

$VAR1 = {
          '8' => [
                   '"EMPNO"',
                   '"ENAME"',
                   '"JOB"',
                   '"MGR"',
                   '"HIREDATE"',
                   '"SAL"',
                   '"COMM"',
                   '"DEPTNO"
',
                   '"7839"',
                   '"KING"',
                   '"PRESIDENT"',
                   '""',
                   '"11/17/1981"',
                   '"5000"',
                   '""',
                   '"10"
',

But I'm expecting this instead

$VAR1 = { '"EMPNO"'=>[12,3,4,5,6,7,8,9],
          '"EMPNAME"'=>["pavan","kumar"...],

};
like image 770
pavan Avatar asked Mar 23 '23 07:03

pavan


1 Answers

You are trying to use a slice in a push statement, and that will not work. The array will be in scalar context, which is why you see the key 8. You would need to loop over the keys to push values onto the arrays. However, why do it that way?

You can use the Text::CSV module for this, which is rather simple and probably more appropriate, assuming you have a real csv format.

use strict;
use warnings;
use Data::Dumper;
use Text::CSV;

my $csv = Text::CSV->new({
        binary  => 1,
        eol     => $/,
    });
my %data;
open my $fh, "<", "yourfile.csv" or die $!;
$csv->column_names ($csv->getline($fh));          # get header names

while (my $row = $csv->getline_hr($fh)) {         # get hashref with values
    for my $key (keys %$row) {
        push @{$data{$key}}, $row->{$key};        # store values
    }
}
print Dumper \%data;
like image 58
TLP Avatar answered Mar 31 '23 12:03

TLP