Update: Note to the OP: You provided simple example data, but perhaps too simple. The kind of problems that can crop up in these CSV files are legion. "Fred Smith, MD", "George Bush, Jr" or "Widget, INC". Even parsing phone numbers can be a whole can of worms. Parsing a full blown CSV file is better done with a module because the details are a lot harder than one might think. However, you have another big problem, the XML. But now maybe you can focus on getting XML working and then come back to the CSV part when you discover that neither one of our simple approaches will work with complex data. BTW, kudos to you for providing code that actually compiles and runs albeit with the "wrong' result.
use strict; use warnings; use XML::Writer; use IO::File; use Data::Dumper; my $CSVfile='1.csv'; my ($arrRef,@keys)= convertCsvToHash($CSVfile); print Dumper $arrRef; print Dumper \@keys; sub convertCsvToHash { my $file = shift; my @AoH; open(FILE, "$CSVfile") or die "$!";; my $header = <FILE>; chomp $header; my @keys = split ',',$header; while (my $data=<FILE>) { my %hash; chomp $data; my @values = split ',',$data; foreach my $key (@keys) { $hash{$key} = shift @values; } push @AoH, \%hash; } return \@AoH,@keys; } __END__ $VAR1 = [ { 'Phone' => '1111', 'Name' => 'A', 'Company' => 'X', 'Email' => 'a.x@aol.com' }, { 'Email' => 'b.y@aol.com', 'Company' => 'Y', 'Name' => 'B', 'Phone' => '0' }, { 'Email' => 'c.z@aol.com', 'Phone' => '2222', 'Name' => 'C', 'Company' => 'Z' } ]; $VAR1 = [ [ 'Name', 'Company', 'Email', 'Phone' ] ];
In reply to Re: csv to xml
by Marshall
in thread csv to xml
by vavz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |