Transforming CSV data into a hash using Perl -
i'm new perl. i'm trying create hash csv file.
my csv info looks this:
class="lang-none prettyprint-override">id,name,title,rating 123,andrew,book 1,3 1221,abraham,book 2,4 43,annie,book 3,1
i'd hash this
class="lang-perl prettyprint-override">$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 instead
class="lang-perl prettyprint-override">$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 code i'm using far. csv in output.csv
file , i'm printing hash in 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>) { lastly if /id/ } $labels = $_; #save lastly line label keys chop $labels; while (<results>) { chomp; @array = split /,/; $index = 0; %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;
your desired info construction strange, next should closer want.
you utilize refresher of perldsc
larn more complex info structures.
use strict; utilize warnings; $header = <data>; chomp $header; @headers = split /,/, $header; @records; while (<data>) { chomp; @cols = split /,/; %hash; @hash{@headers} = map [$_], @cols; force @records, \%hash; } utilize data::dump; dd \@records; __data__ id,name,title,rating 123,andrew,book 1,3 1221,abraham,book 2,4 43,annie,book 3,1
outputs:
[ { id => [123], name => ["andrew"], rating => [3], title => ["book 1"] }, { id => [1221], name => ["abraham"], rating => [4], title => ["book 2"] }, { id => [43], name => ["annie"], rating => [1], title => ["book 3"] }, ]
perl csv hash
No comments:
Post a Comment