I'm new to Perl. I'm trying to create a hash from a CSV file.
My CSV data currently looks like this:
id,name,title,rating
123,Andrew,Book 1,3
1221,Abraham,Book 2,4
43,Annie,Book 3,1
I'd like the hash to look like this
$reviews = {
review => [
{
id => [ 123 ],
name => [ Andrew ],
title => [ "Book 1" ],
rating => [ 3 ],
},
{
id => [ 1221 ],
name => [ Abraham ],
title => [ "Book 2" ],
rating => [ 4 ]]
},
{
id => [ 43 ],
name => [ Annie ],
title => [ "Book 3" ],
edition => [ 1 ],
},
]
};
But I'm getting this instead
$VAR1 = {
'123' => {
'name' => 'Andrew',
'title' => 'Book 1',
'id' => '123',
'rating' => '3',
},
'1221' => {
'name' => 'Abraham',
'title' => 'Book 2',
'id' => '1221',
'rating' => '4',
},
'43' => {
'name' => 'Annie',
'title' => 'Book 3',
'id' => '43',
'rating' => '1',
}
};
Here's the code I'm using so far. My CSV is in the output.csv file and I'm printing the hash in the hashr.txt file
my %hash;
open (RESULTS, "output.csv")|| die "Can't open output.csv: $!\n";
open (HASHR, "+>hashr.txt")|| die "Can't open hashr.txt: $!\n";
while (<RESULTS>) {
last if /id/
}
my $labels = $_; #save last line to label keys
chop $labels;
while (<RESULTS>) {
chomp;
my @array = split /,/;
my $index = 0;
my %h = map { $_ => $array[$index++]} split( ",", $labels );
#my $key = "review";
#$hash{$key}=\%h;
$hash{ $array[0] } = \%h;
}
print Dumper(\%hash);
print HASHR Dumper(\%hash);
close RESULTS;
[]which is an anonymous array in perl?$reviewsis a one-element hash, and that your hash values are one-element arrays? So to access, say, thenamefield of the second review you have to write$reviews->{review}[1]{name}[0]. Unless you have more data that you need to store in the same structure, wouldn't it be better if$reviewswas an array reference and your hash values were plain strings? That way, accessing the same item would look like$reviews->[1]{name}which is much simpler and less prone to bugs.