Both Reading and writing to a file
I am new to perl and am trying to read and write to a csv file in perl. But nothing happens can some one help me where the problem is. I am able to read without a problem using '<' but I am unable to write.
use strict;
use warnings;
use Text::CSV_XS;
my $file = 'file.csv';
my $csv = Text::CSV_XS->new();
open (InCSV, '+>>', $file) or die $!;
while (<InCSV>) {
if ($csv->parse($_)) {
my @columns = $csv->fields();
if($columns[1] eq "01") {
my $str = "Selecte开发者_运维知识库d $columns[6] \n ";
push(@columns,$str);
print InCSV join("," , @columns), "\n";
}
} else {
my $err = $csv->error_input;
print "Failed to parse line: $err";
}
}
close InCSV;
Opening a file in +>>
mode will seek to the end of the file, so there will be nothing to read unless you seek
back to the beginning (or the middle) of the file. To open in read/write mode with the file cursor at the beginning of the file, use +<
mode.
That said, you probably want to rethink your approach to this problem. It looks like you are trying to read a row of data, modify it, and write it back to the file. But the way you have done it, you are overwriting the next row of data rather than the row you have just read, and anyway the new data is longer (has more bytes) than the old data. This is certain to corrupt your data file.
Some better approaches might be to
read and process all data first, then close and overwrite the input with processed data
write data to a temporary file while you are processing it, then overwrite the input with the temporary file (see also about the perl interpreter's in-place editing mode)
use a module like
Tie::File
to handle the line-based I/O for this task
精彩评论