in reply to Editing Files In Place
It looks like it should work...
In this small snippet of code you never print your changes back to the file. You read a line in, manipulate it and throw it away. Remember that $_ holds the contents of the line. It is not the line itself.
Your immediate thought might be to add
to the bottom of your while loop, but this won't work either. It won't work because your file pointer telling you where you've read up to has been incremented to the end of the line you've read. So printing out what you've just read will duplicate it in the file.print FETCHMAILRC $_;
What is more, when you print this line back to the file you move the file pointer on again, so your file will end up completely corrupted. A way to get around that is to use seek lots, but that's beginning to get masochistic.
If you don't like merlyn's excellent suggestion (although who wouldn't?) you can also do it this way:
Note that I snuck $! into those die statements too. $! tells you what just went wrong, so rather than just being told that you were unable to open FRMC for reading you'll be told why: file doesn't exist, permission denied etc. If there is any chance whatsoever that more than one process might try to do this at a time then you really must look into locking. There are many excellent nodes around here discussing locking in detail.open(FETCHMAILRC, '< .fetchmailrc') or die "Unable to open FMRC for re +ading. $!"; my $filecontents; while (<FETCHMAILRC>) { s/^here/$username\nhere/i; $filecontents .= $_; } close FETCHMAILRC or die "Close on FMRC died: $!"; # clobber file and open for writing open(FETCHMAILRC, "> .fetchmailrc') or die "Unable to open FMRC for wr +iting. $!"; print FETCHMAILRC $filecontents; close FETCHMAILRC or die "Close on FMRC died: $!";
Hope it helps.
jarich
|
|---|