Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSV into hash

Tags:

hash

perl

I have a csv with the first column a label followed by comma separated values:

LabelA,45,56,78,90
LabelB,56,65,43,32
LabelC,56,87,98,45

I'd like the first column (LabelA etc) to be the Key in a hash with the numeric values in an array.

I can read the file into an array or scalar but I'm not sure what to do after that. Suggestions??

Edit: Ok, so it looks like this assigns the value to a key ..but what about the comma delimited numbers in my example? Where are they going? Are they in %hash ? If so could you maybe dumb down your explanation even further? Thanks.

like image 334
RH. Avatar asked Nov 29 '22 20:11

RH.


1 Answers

Personally, I like the Text::CSV_XS and IO::File module:

use Text::CSV_XS;
use IO::File;

# Usage example:
my $hash_ref = csv_file_hashref('some_file.csv');

foreach my $key (sort keys %{$hash_ref}){
   print qq{$key: };
   print join q{,}, @{$hash_ref->{$key}};
   print qq{\n};
}

# Implementation:
sub csv_file_hashref {
   my ($filename) = @_;

   my $csv_fh = IO::File->new($filename, 'r');
   my $csv = Text::CSV_XS->new ();

   my %output_hash;

   while(my $colref = $csv->getline ($csv_fh))
   {
      $output_hash{shift @{$colref}} = $colref;
   }

   return \%output_hash;
}
like image 136
Todd Gardner Avatar answered Dec 05 '22 05:12

Todd Gardner