in reply to read and write to same file
The easy solution in your case would be to make use of either a temporary file, or to slurp in the entire file into memory. With many systems now having at least 256 Mb of memory, slurping in entire files isn't too bad (although I wouldn't do it with a 5 Gb file). Some untested code:
Do not forget the truncate, this is needed if you have actually deleted any commas - the text to write back will be shorter, and you don't want the trailing old part of the file.use Fcntl 'SEEK_SET'; open my $fh, "+<", $file or die; local $/; local $_ = <$fh>; s/,(?=\n|$)//g; seek $fh, 0, SEEK_SET or die; print $fh $_ or die; truncate $fh, tell $fh or die; close $fh or die;
And for a one-liner:
perl -pi -le 'BEGIN{$/=",\n"}' file
|
|---|