in reply to read and write to same file

In general, to read/write to a file, you need to open the file read/write, and if you want to write back a line you just read, you need to seek back to the beginning for the line before writing. But it gets complicated if the line you are writing back have a different length. On Unix and Windows, files are just streams of bytes, neither the OS, nor the filesystem have any concept of a "lines" - lines are there for us humans.

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:

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;
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.

And for a one-liner:

perl -pi -le 'BEGIN{$/=",\n"}' file