Question

I have a .csv file which contains only one line. Say the file name is new.csv and the line in that is > abc,add,aer,adfw,asdf

Now I'm trying to read this file and then trying to append another data to that by writing to that same file like this.

open(FH , '+<' , "") or die "Cannot open the file : $!"
while(<FH>){
    chomp($_);
    print FH ", new_data"; 
}
close(FH)

By running this

Expected output :

abc,add,aer,adfw,asdf, new_data

Actual output :

abc,add,aer,adfw,asdf new_data

That is the new data is getting added to a new line even though i used the chomp on $_.

The other things I've tried out is

  1. I tried writing to a brand new file and then use the system() function to replace the new file with the old one.

  2. I tried using join function and string concatenation function.

  3. I tried sending the line to a new variable and then appending data and then writing to the file.

All of them have failed.

Thanks for you help.

Sai Pavan Yaraguti

Was it helpful?

Solution 2

even though i used the chomp on $_.

In your case, that $_ is an in-memory copy of current input line, so chomp will not change the corresponding line of input file.

One way to change file in place is using Tie::File, which will tie a regular file to an array, so you can modify that file by changing that array.

Here is an example:

#!/usr/bin/perl

use strict;
use warnings;

use Tie::File;

my $file = 'new.csv';

tie my @line, 'Tie::File', "$file" or die "Cannot tie $file: $!";

$line[0] .= ', new_data';

untie @line;

OTHER TIPS

In general it is best to write your output to a new file, as there are a number of problems with reading and writing to the same file at once.

However, in the case of a file containing a single line of text it can be done relatively safely.

This program shows the idea. The call to seek is there to move the pointer back to the beginning of the file, as otherwise it will be left pointing after the end of the line of text, which is why your own attempt left the line with its trailing newline still instact.

The truncate call is there to empty the file, so as to make the operation safer. If there was anything in the file after the first line then it will be removed.

use strict;
use warnings;

open my $fh, '+<', 'myfile.csv' or die "Cannot open the file: $!";
my $line = <$fh>;
chomp $line;

seek $fh, 0, 0;
truncate $fh, 0;

print $fh $line, ",new_data\n"; 
close $fh;

output

abc,add,aer,adfw,asdf,new_data
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top