-
Notifications
You must be signed in to change notification settings - Fork 3
Use with Text::CSV
shinobi edited this page Nov 30, 2019
·
10 revisions
If you need to use Text::CSV, the rowset constructor will help you on this.
use Text::CSV;
use Data::StaticTable;
my $t1 = Data::StaticTable.new( csv(in => "myfile.csv") ):data-has-header;
You will probably have to use :data-has-header
. Just make sure that the first line in the csv has this header. Depending on how your csv is constructed, you might lose data if, for example, you have rows with more elements that the ones in your header. If you want to recover them, change the code to this:
use Text::CSV;
use Data::StaticTable;
my %rejected;
my $t1 = Data::StaticTable.new(
csv(in => "myfile.csv"),
rejected-data => %rejected
):data-has-header;
The %rejected
hash will have the row number where the data was discarded as the key, and the value will contain an array with all the rejected elements for that row.
This sub will take care of saving a StaticTable using Text::CSV.
use Text::CSV;
use Data::StaticTable;
sub save-to-csv(StaticTable $st, Str $filename) {
my @csvdata = $st.shaped-array(); # Get all data
unshift @csvdata, $st.header; # Add the header at the top
csv(
in => @csvdata, out=>$filename,
separator=>";", quote_char=>'"', escape_char=>"\\"
);
}