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.
Text::CSV::Hashify
Turn a CSV file into a Perl hash:
Well, let's assume that there are no special characters and so on.
First you open the file:
Then you read from it in loop:
Afterwards, you remove trailing white characters (\n and others):
And split it into array:
When it's in array, you get first element off the array:
And store it in hash:
(\@array means reference to array).
Whole code:
I think this can also work easier.
The $refhashvariable will be a reference to an array of hashes.
Each hash contain the headers (as hashkey) and the values of one CSV line. The array contains the hashes for all lines in the CSV.
This works for me. I have not tried en case the CSV does not have headers.
See perlfunc split and perldsc.
Make a hash of array references:
Your data structure should look like this:
Personally, I like the Text::CSV_XS and IO::File module: