Click to See Complete Forum and Search --> : file manipulation in perl
Rickead2000
01-23-2003, 07:01 PM
HI,
is it possible to open a file in perl and change the contents of just one line?
opening it for overwrite appears to make the file blank.
if i open it in append mode, can it only write to the end of the file?
ideally, i would like to be able to overwrite JUST the line that the file pointer is currently at. e.g.
hello123
hello345 <-pointer here
hello567
is it possible to replace just the line "hello345" without affecting the rest of the file?
takshaka
01-23-2003, 11:59 PM
Old perlfaq5 answer: How do I change one line in a file/delete a line in a file/insert a line in the middle of a file/append to the beginning of a file? (http://www.perldoc.com/perl5.6/pod/perlfaq5.html#How-do-I-change-one-line-in-a-file-delete-a-line-in-a-file-insert-a-line-in-the-middle-of-a-file-append-to-the-beginning-of-a-file-)
New perlfaq5 answer: use Tie::File (http://www.perldoc.com/perl5.8.0/lib/Tie/File.html)
Rickead2000
01-27-2003, 05:37 AM
using the tie::file method i have put
tie @nums, 'Tie::File', $file or dienice("Error! Cannot open $file #!");
but when it gets to this line, it just appears to stop execution.
i nolonger get the following web page printed, just a white screen.
if i rem this line out, all works fine.
i have also untied the array, but to no effect.
does anyone know what it causing this?
Hangdog42
01-27-2003, 01:02 PM
How about a more generic solution:
open(IN, filename);
@fileArray = <IN>;
close(IN);
If you know which line you need to change (x) you can do it with
$fileArray[x] = changedline;
Then just write out the array to a file with the same name
open(OUT,">filename");
foreach $a (@fileArray){
print(OUT $a);
}
close(OUT);
takshaka
01-28-2003, 12:40 AM
Originally posted by Rickead2000
tie @nums, 'Tie::File', $file or dienice("Error! Cannot open $file #!");
but when it gets to this line, it just appears to stop execution.
Unless you've omitted the 'use Tie::File;' line, I can't guess without an error message. You'll have to look in the server's error log since this is apparently a CGI script.
btw--that should be $! instead of #!.
Originally posted by Hangdog42
foreach $a (@fileArray){
print(OUT $a);
}
No need for the loop:
print OUT @fileArray;