Accessing data stored in .CSV file

90 views Asked by At

I have written a very simple script that is supposed to output the 2nd element of the 2nd line of a CSV file. However, when I run it I get the following error message: "Uncaught exception from user code: CSV parse error: EIF - CR char inside unquoted, not part of EOL at csv.tester1.pl line 13"

What am I doing wrong?

This is the actual code:

#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;

use Tie::Array::CSV;

tie my @data, 'Tie::Array::CSV', 'ExampleData.csv';

my $length = scalar(@data);
print $length;
print "\n";
print $data[1][1];

while the data file is called ExampleData.csv and is:

25201927,5.62963E+14,B,100,203300,P
25201928,5.62963E+14,D,0,0,P
25201928,5.62963E+14,B,400,202500,P
1

There are 1 answers

1
Borodin On BEST ANSWER

I suspect that this is due to the CSV file originating on Windows but being processed on a different platform

Tie::Array::CSV hard codes the record separator as LF, which is correct for almost any situation (including Windows files being processed on a Windows system) but the records of a Windows file processed non-natively will appear to end in CR LF. The module will strip only the LF, leaving a spurious CR at the end of the last field

If my conjecture is correct (I can't test at present as the system disk on my Windows machine died this afternoon) then you can change the record separator to CR LF by writing

tie my @data, 'Tie::Array::CSV', 'ExampleData.csv', tie_file => { recsep => "\r\n" };

I hope this helps