Wanted: a convenient shorthand for when the first line of a CSV contains column names
skington opened this issue · comments
I do a lot of converting spreadsheets to CSV, schlepping them to a server, then going through them. I find myself writing code like this all the time:
open(my $fh, '<', ...);
my $csv = Text::CSV->new;
$csv->column_names(@{ $csv->getline($fh) });
while (my $data = $csv->getline_hr($fh)) {
...
}
It's line three that particularly bothers me. Why do I have to type this all the time? (Although passing $fh around all the time is annoying as well.)
I'd really like to be able to say something like e.g.
my $csv = Text::CSV->new_from_file(...);
while (my $data = $csv->data) {
...
}
(It occurs to me, as I write this, that a module called e.g. Text::CSV::FromFile could implement this functionality very simply and elegantly, and I might end up writing something like that when I get a few tuits.)
Text::CSV::StandardHeader is probably a better name for this, as that would cover reading from a scalar ref as well. And $csv->header($fh) is probably a better shorthand in line 3.
Basically, Text::CSV is just a wrapper of Text::CSV_XS, and we won't add anything until Text::CSV_XS adds it.
I don't particularly think your proposed method fits Text::CSV(_XS) well because Text::CSV(_XS) has a more convenient csv
function (see esp. https://github.com/Tux/Text-CSV_XS/blob/master/CSV_XS.pm#L3417-L3423), but if you really need more discussion, could you start it there?