Reputation: 21
I am trying to create a CSV file which reads in a CSV file and then outputs the data in the format:
Type: ABC
A: Hello
B: World
C: Test-Data, Testing
Type: ABC
A: Hello
B: World
C: Test-Data, Testing
With the input data looking like this
0: "ABC", "Hello", "World", "Test-Data, Testing"
1: "ABC", "Hello", "World", "Test-Data, Testing"
I started off by reading the Text:CSV and then created
use strict;
use warnings;
use Text::CSV;
my $file = 'file.csv';
my $csv = Text::CSV->new ({ binary => 1, eol => $/});
open my $input, "<", $file or die "$file: $!";
while (my $row = $csv->getline ($input){
next if ($. == 1);
if ($csv->parse($_))
{
print "variable: $_";
my @columns = $csv->fields();
print "Type: $columns[0]\n\t A: $columns[1]\n\t B:$columns[2] \n\t C:$columns[3]";
}
else
{
my $error = $csv->error_diag;
print "Failed to parse line: $error";
}
}
Though it doesn't seem to be working, I thought it would read in the file.csv to $file and then loop around the the while loop using the getline to read in each line of the file.
What am i missing here? I was wondering if anyone would be able to help; I have tried to include as much information as possible.
Upvotes: 2
Views: 1651
Reputation: 67900
Your mistake is trying to parse a line which is already parsed:
while (my $row = $csv->getline ($input){ # your row is now in $row
....
if ($csv->parse($_)) # Wrong! This is already done with getline()
Simply remove your erroneous code in the if/else
clause and use
my @columns = @$row;
And your print statement should work just fine.
Upvotes: 4