Tux / Text-CSV_XS

perl5 module for composition and decomposition of comma-separated values
17 stars 20 forks source link

Add an option to the csv function to neither return nor print anything #13

Closed choroba closed 6 years ago

choroba commented 6 years ago

Let's say I just want to populate a structure in after_parse or on_in, but I don't want to get the whole structure back, and I don't want to print it. E.g. I might want to accumulate information by id:

csv (in      => shift,
     headers => "skip",
     on_in   => sub {
         my ($id, $email) = @{ $_[1] };
         push @{ $by_id{$id}{email} }, $email;
         },
    );

I'm only interested in %by_id. Something like out => undef or similar.

Tux commented 6 years ago

I needed that often too, and worked around that by just assigning it to an unused scalar

my $void = (in => [[1,2]], on_in => sub { ...});

It is relatively easy to support undef too, but that would prevent me to cast errors on invalid out, like

my $out;
csv (in    => [[1,2]],
     out   => $out, # Needs to be a reference
     on_in => sub { $cache{$_[1][1]++ },
    );

Using a reference like \undef would break

out => \my $buffer,

so, that is not an option. How about using the same as in after_parse:

csv (in    => [[1,2]],
     out   => \"skip",
     on_in => sub { $cache{$_[1][1]++ },
    );

As the current implementation does not warn on out => 0 (or out being anything false), it would be backward compatible to promote this to a feature as you requested, which only inhibits the warning as proposed in my first example, which is not present now. That is now pushed. Feedback welcome.

choroba commented 6 years ago

Yes, thanks a lot, \'skip' is nice, especially as it's something already present elsewhere. I assigned it to a variable, too, but it wasted the memory when the file was large, while the structure being collected was much smaller.

Tux commented 6 years ago

Consider it "patch applied" then. It will be in the next release. Feel free to fetch and test from github. As always, thanks for the feedback. Will close this issue now.