in reply to Writing hashes as records to a CSV file

My variation using csv:

use Text::CSV_XS qw( csv ); my @records = ( { AB1 => 100, NN => 200, XYZ => 400}, { AB1 => 100, XYZ => 400, MM => 300}, ); my %fld = map { $_ => 1 } map { keys %$_ } @records; csv (in => \@records, headers => [ sort keys %fld ]);

A suggestion might be to add quote_empty => 1 to be able to distinguish between missing keys and defined keys. But as that does not shows the difference between missing keys and keys that point to an undefined value, I would suggest something like this (unless you don't care about those differences):

use Text::CSV_XS qw( csv ); my @records = ( { AB1 => 100, NN => 200, XYZ => 400 }, { AB1 => 200, XYZ => 400, MM => 300 }, { AB1 => 300, XYZ => undef, MM => "" }, ); my %seen; my @fld = sort grep { !$seen{$_}++ } map { keys %$_ } @records; csv (in => \@records, headers => \@fld, quote_empty => 1, on_in => sub + { foreach my $f (@fld) { exists $_{$f} or $_{$f} = "--missing--"; } });

->

AB1,MM,NN,XYZ 100,--missing--,200,400 200,300,--missing--,400 300,"",--missing--,

To answer LanX' question: as CSV is streaming, you don't know what is to come, so there is no builtin functionality to find unique values in CSV, but there are enough builtin features to do it yourself.


Enjoy, Have FUN! H.Merijn