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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.