Search code examples
csvperlfilehandle

Can I use Text::CSV_XS to parse a csv-format string without writing it to disk?


I am getting a "csv file" from a vendor (using their API), but what they do is just spew the whole thing into their response. It wouldn't be a significant problem except that, of course, some of those pesky humans entered the data and put in "features" like line breaks. What I am doing now is creating a file for the raw data and then reopening it to read the data:

open RAW, ">", "$rawfile" or die "ERROR: Could not open $rawfile for write: $! \n";
print RAW $response->content;
close RAW;

my $csv = Text::CSV_XS->new({ binary=>1,always_quote=>1,eol=>$/ });
open my $fh, "<", "$rawfile" or die "ERROR: Could not open $rawfile for read: $! \n";

while ( $line = $csv->getline ($fh) ) { ...

Somehow this seems ... inelegant. It seems that I ought to be able to just read the data from the $response->content (multiline string) as if it were a file. But I'm drawing a total blank on how do this. A pointer would be greatly appreciated. Thanks, Paul


Solution

  • You could use a string filehandle:

    my $data = $response->content;
    open my $fh, "<", \$data or croak "unable to open string filehandle : $!";
    my $csv = Text::CSV_XS->new({ binary=>1,always_quote=>1,eol=>$/ });
    while ( $line = $csv->getline ($fh) ) { ... }